Learn to integrate Supabase authentication in your Next.js app with this step-by-step guide covering project setup, API keys, and a basic auth UI.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up a Next.js Project
First, ensure you have Node.js installed on your computer. You can download it from nodejs.org. Once installed, open your terminal and create a new Next.js project by running:
npx create-next-app@latest supabase-nextjs-auth
cd supabase-nextjs-auth
This will create a new Next.js project in a folder named supabase-nextjs-auth
.
Step 2: Create a Supabase Account and Project
Visit the Supabase website and sign up for an account if you haven't already. Once you’re logged in:
Step 3: Obtain Supabase URL and Anon Key
In your Supabase project dashboard:
Step 4: Install Supabase Client Library
In your Next.js project directory, install the Supabase JavaScript client library:
npm install @supabase/supabase-js
Step 5: Configure Supabase Client
Create a new file named supabaseClient.js
in the root of your Next.js project to initialize the Supabase client with the URL and anon key you obtained earlier:
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON\_KEY';
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
Replace YOUR_SUPABASE_URL
and YOUR_SUPABASE_ANON_KEY
with your actual Supabase URL and anon key.
Step 6: Set Up Authentication UI
Now, create a basic authentication UI. For instance, you can modify the pages/index.js
file to handle sign-up and sign-in:
import { supabase } from '../supabaseClient';
import { useState } from 'react';
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.message);
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.message);
else console.log('User signed in:', user);
};
return (
setEmail(e.target.value)}
/>
setPassword(e.target.value)}
/>
);
}
Step 7: Run the Application
Now you can run your Next.js application to test the authentication setup:
npm run dev
This command starts your server and opens your application at http://localhost:3000
. You should see your authentication UI where you can sign up and sign in using email and password.
With these steps, you have successfully set up Supabase authentication in a Next.js application!
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.