P粉9869374572023-08-14 09:29:48
Assuming you are using Next-Auth for authentication:
Wrap the middleware using withAuth
and authenticate the session using the token variable provided by Next-Auth, then redirect to your desired route
based on the validity of the session.
Here is a TS code that may help:
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).*)', ], };