How to create a reuseable protected route in Next.js

Viewed 22

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?

0 Answers
Related