Authentication with Supabase in Next.js

Authentication with Supabase in Next.js

Authentication is a critical aspect of many web applications, and integrating it seamlessly is essential. In this tutorial, we’ll explore how to implement user authentication in a Next.js application using Supabase, a powerful open-source Firebase alternative. Supabase provides a real-time database and authentication out of the box, making it an excellent choice for building robust applications.

Setting Up Supabase

Before we dive into the Next.js integration, let’s set up a Supabase project:

1. Create a Supabase Account

If you haven’t already, sign up for a Supabase account at supabase.io. Once registered, create a new project from the dashboard.

2. Retrieve API Key

After creating the project, navigate to the project settings and retrieve your API key. You’ll need this key to connect your Next.js application to Supabase.

Integrating Supabase in Next.js

Now, let’s integrate Supabase authentication into a Next.js project:

1. Install Required Packages

Install the Supabase JavaScript client in your Next.js project:

npm install @supabase/supabase-js

or

yarn add @supabase/supabase-js

2. Set Up Supabase Client

Create a file named supabase.js to set up the Supabase client:

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

const supabaseUrl = 'https://your-project-id.supabase.co';
const supabaseKey = 'your-api-key';

export const supabase = createClient(supabaseUrl, supabaseKey);

3. Implement Authentication in Next.js

Now, let’s create a component that handles user authentication. Create a file named AuthComponent.js:

// components/AuthComponent.js
import { supabase } from '../path-to-supabase';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';

const AuthComponent = ({ children }) => {
  const [user, setUser] = useState(null);
  const router = useRouter();

  useEffect(() => {
    const session = supabase.auth.session();

    setUser(session?.user ?? null);

    const { data: authListener } = supabase.auth.onAuthStateChange(async () => {
      const newSession = supabase.auth.session();
      setUser(newSession?.user ?? null);

      // Redirect to login if no user is present
      if (!newSession?.user) {
        router.push('/login');
      }
    });

    return () => {
      authListener.unsubscribe();
    };
  }, [router]);

  return <>{user ? children : null}</>;
};

export default AuthComponent;

4. Protect Routes with Authentication

Now, you can protect routes by wrapping them with the AuthComponent. For example, in your profile page:

// pages/profile.js
import AuthComponent from '../components/AuthComponent';

const Profile = () => {
  return (
    <AuthComponent>
      <div>
        <h1>User Profile</h1>
        {/* Your profile content */}
      </div>
    </AuthComponent>
  );
};

export default Profile;

Conclusion

With Supabase, integrating authentication into your Next.js application becomes straightforward. The real-time capabilities of Supabase make it a robust choice for applications requiring seamless user authentication. Experiment with additional Supabase features like real-time database updates to enhance your application further.


© 2023. All rights reserved.