假設(shè)您正在使用Next-Auth進(jìn)行身份驗(yàn)證:
使用withAuth
包裝中間件,並使用Next-Auth提供的token變數(shù)驗(yàn)證會(huì)話,然後根據(jù)會(huì)話的有效性重定向到您想要的route
。
這是一個(gè)可能有幫助的TS程式碼:
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).*)', ], };