Search code examples
authenticationnext.jsnext-auth

How to protect multiple routes from unauthorized access in Next.js using next-auth


I am using Next.js and I have a folder learning inside my pages folder. Now, this learning folder has about 10 pages.

All these pages need to redirect to the index page if the user is not logged in. The following code does the job, but is there any other way to protect multiple pages, so that I don't need to add this same code again and again to all the pages ?

export async function getServerSideProps(context) {
    //redirect to index page if not logged in
    const session = await unstable_getServerSession(context.req, context.res, authOptions);
    if (!session) {
        return {
            redirect: {
                destination: '/',
                permanent: false
            }
        }
    }
}

Solution

  • I believe you are confused between protecting pages and protecting API ROUTES.

    If you simply want to protect pages, you can indeed use middleware

    However, if you wish to protect API Routes (e.g prevent a user from deleting data using your API endpoint and postman), I believe you need to use this unstable_getServerSession

    Except creating reusable function, it's true that I didn't find anywhere in the doc how to set it for multiple paths in one folder only...