website-01/middleware.ts

36 lines
1.0 KiB
TypeScript
Raw Normal View History

2026-06-22 14:43:46 +08:00
import { NextResponse, type NextRequest } from 'next/server';
const TOKEN_COOKIE = process.env.NEXT_PUBLIC_TOKEN_KEY ?? 'admin_token';
/**
* Edge
* - /admin/login
* - /admin token cookie
*
* token adminStore cookie
* "是否已登录" JWT
*/
export function middleware(req: NextRequest): NextResponse {
const { pathname, search } = req.nextUrl;
if (!pathname.startsWith('/admin')) {
return NextResponse.next();
}
if (pathname === '/admin/login') {
return NextResponse.next();
}
const token = req.cookies.get(TOKEN_COOKIE)?.value;
if (!token) {
const url = req.nextUrl.clone();
url.pathname = '/admin/login';
url.searchParams.set('redirect', encodeURIComponent(pathname + search));
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin/:path*'],
};