Maison > Questions et réponses > le corps du texte
P粉9869374572023-08-14 09:29:48
En supposant que vous utilisez Next-Auth pour vous authentifier :
Utilisez withAuth
包装中间件,并使用Next-Auth提供的token变量验证会话,然后根据会话的有效性重定向到您希望的route
.
Voici un code TS qui peut vous aider :
import { NextResponse } from 'next/server'; import { withAuth, NextRequestWithAuth } from 'next-auth/middleware'; export default withAuth(function middleware (request: NextRequestWithAuth) { const session = request?.nextauth?.token; if (request.nextUrl.pathname === '/') return NextResponse.next(); if (!session && request.nextUrl.pathname !== '/login') return NextResponse.redirect(new URL('/login', request.url)); if (session && request.nextUrl.pathname !== '/dashboard') return NextResponse.redirect(new URL('/dashboard', request.url)); return NextResponse.next(); }, { callbacks: { authorized: () => true, }, }); export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], };