#Check authentication using next-auth
1 messages · Page 1 of 1 (latest)
To check if the token is available in the middleware of the Next.js app router, you can use the req.cookies object to access the authentication token. Here's an example of how you can implement this in your middleware:
export function middleware(req) {
const nextUrl = req.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (req.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', req.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', req.url))
}
}
}
In this example, req.cookies.authToken is used to check if the authentication token is present. If it is, the user is redirected to the authenticated dashboard, otherwise, they are redirected to the public dashboard.
Remember, middleware in Next.js helps you control who can access different parts of your website. This is important for keeping areas like the user dashboard protected while having other pages like marketing pages be public. It's recommended to apply Middleware across all routes and specify exclusions for public access.
For more details, you can refer to the Next.js documentation on Middleware (https://nextjs.org/docs/app/building-your-application/routing/middleware) and the Next.js documentation on Link component with Middleware (https://nextjs.org/docs/app/api-reference/components/link#middleware).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@dire talon kapa.ai is still learning and improving, please let us know how it did by reacting below