Implement Protected Routes for Authenticated Users with Supabase Auth

Jon Meyers
InstructorJon Meyers
Share this video with your friends

Social Share Links

Send Tweet

Since Supabase requires our user to be authenticated to fetch tweets, it doesn't make sense for an unauthenticated user to visit the landing page. In this lesson, we implement protected routes that are only accessible to authenticated users.

Additionally, we create a /login route to redirect unauthenticated users, which allows them to sign in with GitHub.

Code Snippets

Redirect unauthenticated users

const {
  data: { session },
} = await supabase.auth.getSession();

if (!session) {
  redirect("/login");
}

Resources

Instructor: Currently, a user sees a list of tweets when they're signed in, but when they sign out, they just see this empty array. It doesn't really make sense for someone to visit this page unless they're signed in. Let's redirect unauthenticated users to a login page.

Back over in our application, before we get a list of tweets from Supabase, we're going to add our redirection logic. We can start by getting some data, which is our session, by awaiting a call to supabase.auth.getSession. This will give us back our user's session, or null if they're not signed in.

If we don't have a session, then we want to redirect the use. This is a function that comes in from next /navigation. We then just need to give it a path to redirect to. In this case that would be /login, which we'll create in a moment.

Then if we do have a session, then we'll continue on to get our tweets from Supabase and then render our component. Let's create this login route. Under app, we want a new file at login/page.tsx.

It's going to export a default async function for login. It's going to need a Supabase client, so we can create that by calling the createServerComponentClient function, which comes in from our auth helpers package. We should know this by now, it takes a cookies function, which we can import from next/headers.

Then it doesn't really make sense for someone to visit our login page if they're already authenticated. We're going to do the reverse of our redirection logic from our landing page. If we do have a session, then we want to redirect to our landing page.

If we don't have a session, then we want to return a login button, so we can just reuse our auth button client component, which comes in from ../auth-button-client.

It then takes a session prop, which can be set to our user's session, which will just be the value null at this point, otherwise we would have been redirected above. Now, if we go back to the browser and refresh, you'll see I've already been redirected to /login because I'm not currently authenticated.

If I log in, it's going to redirect me to that landing page. Again, if I log out, we're back on our login route.