DEV Community

Brayan
Brayan

Posted on

Integrating Supabase with Next.js: A Step-by-Step Guide

Integrating Supabase with Next.js: A Step-by-Step Guide

Introduction

Integrating Supabase with Next.js allows developers to build powerful, scalable applications with ease. Supabase provides a backend-as-a-service platform that includes authentication, real-time subscriptions, and serverless functions, making it an excellent choice for modern web applications. In this tutorial, we'll walk through the process of setting up Supabase with Next.js, covering authentication, database setup, real-time subscriptions, and serverless functions.

Setting Up Supabase

Step 1: Create a Supabase Project

  1. Go to Supabase and sign up for an account.
  2. Create a new project and note down the API URL and the public API key.

Step 2: Install Supabase Client

In your Next.js project, install the Supabase client:

npm install @supabase/supabase-js
Enter fullscreen mode Exit fullscreen mode

Authentication with Supabase

Step 3: Configure Authentication

  1. In the Supabase dashboard, navigate to the Authentication section.
  2. Enable the desired authentication providers (e.g., Email, Google, GitHub).

Step 4: Implement Authentication in Next.js

Create a new file supabaseClient.js to initialize the Supabase client:

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://your-supabase-url.supabase.co';
const supabaseAnonKey = 'your-anon-key';

export const supabase = createClient(supabaseUrl, supabaseAnonKey);
Enter fullscreen mode Exit fullscreen mode

Use the Supabase client in your Next.js pages to handle authentication:

import { supabase } from '../supabaseClient';

export default function LoginPage() {
  const handleLogin = async () => {
    const { user, error } = await supabase.auth.signIn({
      email: 'user@example.com',
      password: 'password',
    });
    if (error) console.error('Error logging in:', error);
    else console.log('Logged in user:', user);
  };

  return <button onClick={handleLogin}>Log In</button>;
}
Enter fullscreen mode Exit fullscreen mode

Database Setup

Step 5: Create Tables and Insert Data

  1. In the Supabase dashboard, navigate to the Database section.
  2. Create tables and insert initial data using the SQL editor.

Step 6: Query Data in Next.js

Use the Supabase client to query data:

import { supabase } from '../supabaseClient';

export async function getServerSideProps() {
  const { data, error } = await supabase.from('your_table').select('*');
  if (error) console.error('Error fetching data:', error);
  return { props: { data } };
}
Enter fullscreen mode Exit fullscreen mode

Real-time Subscriptions

Step 7: Set Up Real-time Subscriptions

Use Supabase's real-time capabilities to subscribe to changes:

import { useEffect } from 'react';
import { supabase } from '../supabaseClient';

export default function RealTimeComponent() {
  useEffect(() => {
    const subscription = supabase
      .from('your_table')
      .on('INSERT', payload => {
        console.log('New row added:', payload.new);
      })
      .subscribe();

    return () => {
      supabase.removeSubscription(subscription);
    };
  }, []);

  return <div>Real-time updates will appear in the console.</div>;
}
Enter fullscreen mode Exit fullscreen mode

Serverless Functions

Step 8: Deploy Serverless Functions

  1. In the Supabase dashboard, navigate to the Functions section.
  2. Create a new function using the SQL editor or upload a function file.

Step 9: Call Serverless Functions from Next.js

Use the Supabase client to call serverless functions:

import { supabase } from '../supabaseClient';

export async function callFunction() {
  const { data, error } = await supabase.functions.invoke('your_function_name', {
    body: { key: 'value' },
  });
  if (error) console.error('Error calling function:', error);
  return data;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Integrating Supabase with Next.js provides a robust solution for building modern web applications. By following this step-by-step guide, you can set up authentication, manage your database, implement real-time subscriptions, and deploy serverless functions with ease. Supabase's comprehensive features and seamless integration with Next.js make it a powerful choice for developers looking to build scalable and efficient applications.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay