0

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
            }
        }
    }
}
IGnyte
  • 210
  • 1
  • 8
Bilal Mohammad
  • 129
  • 1
  • 13
  • You could create a higher-order function that you'd reuse on each page. See [Create a HOC (higher order component) for authentication in Next.js](https://stackoverflow.com/a/66088247/1870780). – juliomalves Oct 11 '22 at 17:43

2 Answers2

3

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...

Zach Bkh
  • 66
  • 5
0

you can use middleware. docs: https://next-auth.js.org/configuration/nextjs#middleware

Create a middleware.ts (or .js) file at the root or in the src directory (same level as your pages).

If you only want to secure certain pages, export a config object with a matcher:

export { default } from "next-auth/middleware"
// otherwise your app would require authentication for all
export const config = { matcher: ["/dashboard"] }

Now you will still be able to visit every page, but only /dashboard will require authentication.

If a user is not logged in, the default behavior is to redirect them to the sign-in page.

that example is from the docs. You can also write a custom middleware

import { NextResponse } from "next/server";
export function middleware(req) {
  const sessionCookie = req.cookies.get("session");
}
// you could add more if logic for other pages
if (req.nextUrl.pathname.startsWith("/admin ")) {
  if (!sessionCookie) {
    return NextResponse.redirect("/home");
  }
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202