Neil Girardi
Neil Girardi

Reputation: 4913

How to create a reuseable protected route in Next.js

I'm new to Next.js. I'm presently using Supabase magic links for auth. Based on this awesome tutorial, I made one of the pages on my app a protected route. I did this by adding the following code to the page file:

export async function getServerSideProps({ req }) {
    const { user } = await supabase.auth.api.getUserByCookie(req)
    if (!user) {
        return { props: {}, redirect: { destination: '/signin' } }
    }
    return { props: {user} }
}

It works well. However, I would need to copy paste this to any other page that I want to be a protected route. Is there a way to make this DRY so that can I make specific pages protected routes without copying this code every time?

I tried making a ProtectedRoute component with this code snippet. However, since it's a component and not a page, getServerSideProps never gets called. Is there an idiomatic way to do this in Next.js?

Upvotes: 0

Views: 1914

Answers (2)

user19693095
user19693095

Reputation:

You can use next.js middleware. More info: https://engineering.udacity.com/protected-routes-using-next-js-edge-middleware-supabase-f197ba7f503c

// src/middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export const middleware = async (request: NextRequest) => {
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    const authCookie = request.cookies.get('supabase-auth-token');
    if (!authCookie) return NextResponse.redirect(new URL('/', request.url));
  }
};

Upvotes: 2

thorwebdev
thorwebdev

Reputation: 1152

For this you can use the Supabase Auth Helpers: https://github.com/supabase/auth-helpers/blob/main/packages/nextjs/README.md

They provide a withPageAuth function for SSR: https://github.com/supabase/auth-helpers/blob/main/packages/nextjs/README.md#server-side-rendering-ssr---withpageauth

import { withPageAuth } from '@supabase/auth-helpers-nextjs';

export default function Profile({ user }) {
  return <div>Hello {user.name}</div>;
}

export const getServerSideProps = withPageAuth({ redirectTo: '/signin' });

Upvotes: 1

Related Questions