Reputation: 1235
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:
Upvotes: 2
Views: 1131
Reputation: 49351
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
}
Upvotes: 1