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

Introduction

Integrating Supabase with Next.js allows developers to build powerful applications with real-time capabilities and serverless functions. In this tutorial, we will cover the essential steps to set up authentication, database management, real-time subscriptions, and serverless functions using Supabase in a Next.js application.

Prerequisites

Before we begin, ensure you have the following:

  • Node.js installed on your machine
  • A Supabase account and a project set up
  • Basic knowledge of Next.js and React

Step 1: Setting Up Your Next.js Project

First, create a new Next.js project if you haven't already:

npx create-next-app@latest my-supabase-app
cd my-supabase-app

Step 2: Installing Supabase Client

Next, install the Supabase client library:

npm install @supabase/supabase-js

Step 3: Configuring Supabase

Create a new file named supabaseClient.js in the root of your project to initialize the Supabase client:

// 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);

Make sure to add your Supabase URL and Anon Key to your environment variables in a .env.local file:

NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key

Step 4: Implementing Authentication

To implement authentication, create a simple login form in your Next.js application:

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

const Login = () => {
  const [email, setEmail] = useState('');

  const handleLogin = async (e) => {
    e.preventDefault();
    const { error } = await supabase.auth.signIn({ email });
    if (error) console.error('Error logging in:', error);
  };

  return (
    <form onSubmit={handleLogin}>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
      <button type="submit">Login</button>
    </form>
  );
};

export default Login;

Step 5: Setting Up the Database

In your Supabase dashboard, navigate to the SQL editor and create a new table:

CREATE TABLE messages (
  id SERIAL PRIMARY KEY,
  content TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);

Step 6: Real-time Subscriptions

To listen for real-time updates, you can set up a subscription in your component:

// components/MessageList.js
import { useEffect, useState } from 'react';
import { supabase } from '../supabaseClient';

const MessageList = () => {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const fetchMessages = async () => {
      const { data } = await supabase.from('messages').select();
      setMessages(data);
    };

    fetchMessages();

    const subscription = supabase
      .from('messages')
      .on('INSERT', (payload) => {
        setMessages((prev) => [...prev, payload.new]);
      })
      .subscribe();

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

  return (
    <ul>
      {messages.map((msg) => (
        <li key={msg.id}>{msg.content}</li>
      ))}
    </ul>
  );
};

export default MessageList;

Step 7: Using Serverless Functions

Next.js supports API routes, which can be used as serverless functions. Create a new API route to handle message submissions:

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

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { content } = req.body;
    const { data, error } = await supabase.from('messages').insert([{ content }]);
    if (error) return res.status(500).json({ error: error.message });
    return res.status(200).json(data);
  }
  res.setHeader('Allow', ['POST']);
  res.status(405).end(`Method ${req.method} Not Allowed`);
}

Conclusion

In this tutorial, we covered how to integrate Supabase with Next.js, including authentication, database setup, real-time subscriptions, and serverless functions. With these tools, you can build robust applications that leverage the power of real-time data and serverless architecture.

Tags

nextjs, supabase, authentication, real-time, serverless