2

Initial situation: I have two server-side cookies (httponly) named accessToken and refreshToken. The payload looks like this:

{
   "user":{
      "firstname":"John",
      "lastname":"Doe",
      "roles":[
         "accounting",
         "supporter"
      ]
   }
}

Goal: Handle server-side authorization with Next.js 13 (app folder-based). Some routes should be protected and only accessible to some users with specific roles.

Example:

  • GET /login should be accessible to everyone
  • GET /dashboard for authorized users only
  • GET /accounting only for users with the accounting role
  • GET /admin only for users with the role admin
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
hantoren
  • 357
  • 2
  • 17

1 Answers1

1

you could write a middleware. in next13 middleware file is in the same directory as package.json and it should be middleware.js (or .ts).

export async function middleware(req: NextRequest, res: NextResponse) {
  // get all the cookies
  let cookies = req.cookies.getAll();
  // read those cookies. based on cookies you decide which paths can be visited
  const isAuthorized="define logic if the the user authorized"
  console.log("req.pathname", req.nextUrl.pathname);
  const currentPath = req.nextUrl.pathname;
  if (currentPath==="/dashboard" && isAuthorized ){
    // you allow the user to visit this page
    return NextResponse.next()
  }
  // similarly add logic for other cases 
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202