website-01/middleware.ts
2026-06-22 14:43:46 +08:00

36 lines
1.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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*'],
};