Rumah > Soal Jawab > teks badan
P粉9869374572023-08-14 09:29:48
Dengan mengandaikan anda menggunakan Next-Auth untuk mengesahkan:
Gunakan withAuth
包装中间件,并使用Next-Auth提供的token变量验证会话,然后根据会话的有效性重定向到您希望的route
.
Berikut ialah kod TS yang boleh membantu:
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).*)', ], };