I'm implementing a Nextjs middleware to redirect unauthenticated users to the login page. It's currently working locally, but not on the remote server:
export async function middleware(req: NextRequest) {
const { cookies } = req
if (!cookies['next-auth.session-token.0']) {
return NextResponse.rewrite(new URL('/login', req.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/account/:path*'],
}
My setup includes Nextjs version 12.1.6 and next-auth version 4.10.0.
The .get()
method mentioned in the Next docs for retrieving tokens from headers or cookies is not available in these versions.
The _middleware.ts
file is located in a subfolder within the pages directory.