我创建了一个文件routes.ts来存储我想要保护的路由。这对常规路由有效,比如我的“/profile”路由,但是当我尝试添加动态url时,它不起作用(未经身份验证的用户仍然可以查看这些路由)。
routes.ts
export const protectedRoutes = ["/profile", "/profile/[id]", "/timeline/[id]", "/"];
export const authRoutes = ["/login"];
export const publicRoutes = [];
middleware.ts
export function middleware(request: NextRequest) {
const currentUser = request.cookies.get("currentUser")?.value;
if (
protectedRoutes.includes(request.nextUrl.pathname) &&
(!currentUser || Date.now() > JSON.parse(currentUser).expiredAt)
) {
request.cookies.delete("currentUser");
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("currentUser");
return response;
}
if (authRoutes.includes(request.nextUrl.pathname) && currentUser) {
return NextResponse.redirect(new URL("/profile", request.url));
}
}```
I have logged out of my application and tried to view the dynamic routes. If my code was correct, I should have been rerouted to my login page, however, it still shows the data even though I am not authenticated. To make sure the protected routes work, I viewed my static routes, and was successfully rerouted to the login page.
1条答案
按热度按时间holgip5t1#
尝试在中间件中创建一个
config
变量,并将中间件应用到您要保护的路由上。例如,您可以将此变量添加到动态路由的middleware
中:请注意,如果在中间件中包含
config
,中间件将只应用于matcher
数组中的路由。我只是为您的动态路由添加了上述代码作为示例。matcher
是要在其上应用中间件的路由数组。它支持通配符语法,因此您可以为动态路由匹配一组路由。例如,/profile/:path*
部分将在以/profile
开头的所有路由上应用中间件。它将匹配/profile/123
等路由。了解有关config
和matcher
here的更多信息。