Supabase Auth: Next.js Guide
Supabase Auth: Next.js Guide
Hey guys! Today, we’re diving deep into integrating Supabase authentication into your Next.js applications. If you’re looking to add secure and scalable authentication to your Next.js project, you’ve come to the right place. We’ll walk through everything from setting up Supabase, configuring your Next.js app, and implementing various authentication methods. Let’s get started!
Table of Contents
Setting Up Supabase
First things first, you need a Supabase account. Head over to Supabase and sign up. Once you’re in, create a new project. Remember to keep your API keys and URL handy; you’ll need them later. Consider these keys as the master keys to your database, so guard them with your digital life! Supabase is like a Swiss Army knife for backend needs, providing authentication, database, storage, and even real-time functionalities. Once your project is created, navigate to the ‘Authentication’ section in the Supabase dashboard. Here, you can configure various sign-in methods like Email/Password, Google, GitHub, and more. Enabling these providers is usually a no-brainer – just a few clicks and you’re set. But remember to configure the callback URLs correctly in your Supabase project settings. These URLs tell Supabase where to redirect users after they authenticate. If you mess this up, your users will end up in a no-man’s land, and nobody wants that. Also, familiarize yourself with Supabase’s security rules. You can define policies that control who can access what data. This is crucial for ensuring that only authorized users can perform certain actions. Trust me, spending some time here will save you from potential headaches down the road.
Installing Supabase Client in Next.js
Next up, let’s get the Supabase client installed in your Next.js project. Open up your terminal, navigate to your project directory, and run:
npm install @supabase/supabase-js
. This command pulls in the Supabase JavaScript library, which we’ll use to interact with our Supabase backend. Once the installation is complete, create a
.env.local
file in your project’s root directory. This file will store your Supabase URL and API key. Add the following lines to your
.env.local
file, replacing the placeholders with your actual Supabase credentials:
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
Important:
Make sure to prefix these variables with
NEXT_PUBLIC_
so that Next.js exposes them to the browser. Also, never commit your
.env.local
file to your repository. It contains sensitive information that should be kept secret. To initialize the Supabase client, create a
supabaseClient.js
file (or any name you prefer) in your project. This file will contain the code to create and export the Supabase client instance. Inside
supabaseClient.js
, add the following code:
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
export default supabase;
This code imports the
createClient
function from the
@supabase/supabase-js
library, retrieves the Supabase URL and API key from the environment variables, and creates a new Supabase client instance. Finally, it exports the client instance so that you can use it in other parts of your application. Now you’re all set to start using Supabase in your Next.js project! You’ve got the client installed, configured, and ready to roll. Onward!
Implementing Sign-Up
Alright, let’s get users signing up! We’ll create a simple sign-up form in our Next.js app. This form will take the user’s email and password, and then use the Supabase client to create a new user account. First, create a new component called
SignUpForm.js
. Inside this component, add the following code:
import { useState } from 'react';
import supabase from './supabaseClient';
const SignUpForm = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
const { user, error } = await supabase.auth.signUp({
email: email,
password: password,
});
if (error) {
setError(error.message);
} else {
// Handle successful sign-up
console.log('Sign-up successful!', user);
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
{error && <p>{error}</p>}
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
<button type="submit" disabled={loading}>
{loading ? 'Signing Up...' : 'Sign Up'}
</button>
</form>
);
};
export default SignUpForm;
In this code, we’re using the
useState
hook to manage the email and password input fields. The
handleSubmit
function is called when the form is submitted. Inside this function, we call the
supabase.auth.signUp
method to create a new user account. If there’s an error, we display it to the user. If the sign-up is successful, we log a success message to the console.
Don’t forget to handle the successful sign-up appropriately in your application,
like redirecting the user to a dashboard or displaying a confirmation message. To use this component, import it into your page or component where you want to display the sign-up form. For example, in your
pages/index.js
file:
import SignUpForm from '../components/SignUpForm';
const Home = () => {
return (
<div>
<h1>Welcome to My App</h1>
<SignUpForm />
</div>
);
};
export default Home;
Now, when you run your Next.js application, you should see the sign-up form. Users can enter their email and password, and a new user account will be created in your Supabase project. Keep in mind, this is a basic example. You’ll likely want to add more error handling, validation, and UI enhancements to your sign-up form. But hey, it’s a solid start!
Implementing Sign-In
So, users can sign up, but what about signing in? Let’s implement a sign-in form similar to the sign-up form. Create a new component called
SignInForm.js
and add the following code:
import { useState } from 'react';
import supabase from './supabaseClient';
const SignInForm = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
const { user, error } = await supabase.auth.signIn({
email: email,
password: password,
});
if (error) {
setError(error.message);
} else {
// Handle successful sign-in
console.log('Sign-in successful!', user);
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
{error && <p>{error}</p>}
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
<button type="submit" disabled={loading}>
{loading ? 'Signing In...' : 'Sign In'}
</button>
</form>
);
};
export default SignInForm;
This code is very similar to the sign-up form. The main difference is that we’re calling the
supabase.auth.signIn
method instead of
supabase.auth.signUp
. This method takes the user’s email and password and attempts to sign them in. If the sign-in is successful, Supabase returns the user object. You can then use this object to update your application’s state and redirect the user to a protected page. To use this component, import it into your page or component where you want to display the sign-in form. For example, in your
pages/index.js
file:
import SignInForm from '../components/SignInForm';
const Home = () => {
return (
<div>
<h1>Welcome to My App</h1>
<SignInForm />
</div>
);
};
export default Home;
Now, when you run your Next.js application, you should see the sign-in form. Users can enter their email and password, and if the credentials are correct, they will be signed in. Remember to handle the successful sign-in appropriately in your application. This might involve setting a cookie, updating the user’s session, or redirecting them to a different page. Also, consider adding a