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

In this tutorial, we will explore how to integrate Supabase with Next.js, covering essential features such as authentication, database setup, real-time subscriptions, and serverless functions. Supabase is an open-source Firebase alternative that provides a powerful backend for your applications, while Next.js is a popular React framework for building server-rendered applications. By the end of this guide, you will have a fully functional application that leverages the strengths of both technologies.

Prerequisites

Before we begin, ensure you have the following:

  • Node.js installed on your machine
  • A Supabase account (you can sign up for free)
  • Basic knowledge of React and Next.js

Step 1: Setting Up Your Next.js Project

First, create a new Next.js project using the following command:

npx create-next-app supabase-nextjs-integration
cd supabase-nextjs-integration
Enter fullscreen mode Exit fullscreen mode

Next, install the Supabase client library:

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

Step 2: Configuring Supabase

  1. Create a new Supabase project from the Supabase dashboard.
  2. Get your API keys from the project settings. You will need the URL and anon key.
  3. Create a .env.local file in your Next.js project root and add the following:
   NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
   NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
Enter fullscreen mode Exit fullscreen mode

Step 3: Initializing Supabase Client

Create a new file named supabaseClient.js in the lib directory:

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

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

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

Step 4: Implementing Authentication

4.1 Sign Up and Sign In

Create a simple authentication form in pages/index.js:

// pages/index.js
import { useState } from 'react';
import { supabase } from '../lib/supabaseClient';

export default function Home() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSignUp = async () => {
    const { user, error } = await supabase.auth.signUp({ email, password });
    if (error) console.error('Error signing up:', error);
    else console.log('User signed up:', user);
  };

  const handleSignIn = async () => {
    const { user, error } = await supabase.auth.signIn({ email, password });
    if (error) console.error('Error signing in:', error);
    else console.log('User signed in:', user);
  };

  return (
    <div>
      <h1>Supabase Authentication</h1>
      <input type="email" onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
      <input type="password" onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
      <button onClick={handleSignUp}>Sign Up</button>
      <button onClick={handleSignIn}>Sign In</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

4.2 Handling User Session

To manage user sessions, you can use the useEffect hook to listen for authentication state changes:

import { useEffect } from 'react';

useEffect(() => {
  const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
    console.log('Auth event:', event);
    console.log('Session:', session);
  });

  return () => {
    authListener.subscription.unsubscribe();
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Step 5: Setting Up the Database

  1. Create a new table in Supabase called messages with columns id, content, and user_id.
  2. Insert some sample data into the messages table using the Supabase dashboard.

Step 6: Real-time Subscriptions

To listen for changes in the messages table, you can set up a real-time subscription:

useEffect(() => {
  const subscription = supabase
    .from('messages')
    .on('INSERT', payload => {
      console.log('New message:', payload.new);
    })
    .subscribe();

  return () => {
    supabase.removeSubscription(subscription);
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Step 7: Implementing Serverless Functions

Next.js allows you to create serverless functions easily. Create a new file in the pages/api directory called sendMessage.js:

// pages/api/sendMessage.js
import { supabase } from '../../lib/supabaseClient';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { content, user_id } = req.body;
    const { data, error } = await supabase
      .from('messages')
      .insert([{ content, user_id }]);

    if (error) return res.status(400).json({ error: error.message });
    return res.status(200).json(data);
  }
  return res.status(405).json({ message: 'Method not allowed' });
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we covered how to integrate Supabase with Next.js, including authentication, database setup, real-time subscriptions, and serverless functions. This powerful combination allows you to build robust applications with ease. Explore further by adding more features and enhancing your application!

Tags

nextjs, supabase, authentication, real-time, serverless

Top comments (0)