如何为next.js中间件创建动态的、受保护的路由



我已经创建了一个文件routes。里面有我想保护的路线。这适用于常规路由,例如我的'/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.

尝试在中间件中创建一个config变量,并在你想要保护的路由上应用该中间件。例如,您可以将以下内容添加到动态路由的middleware中:

export const config = {
matcher: ["/profile/:path*", "/timeline/:path*"]
};

请注意,如果在中间件中包含config,则中间件将仅应用于matcher数组中的路由。我只是为你的动态路由添加了上面的代码作为一个例子。

matcher是应用中间件的路由数组。它支持通配符语法,因此您可以为动态路由匹配一组路由。例如,/profile/:path*部分将在所有以/profile开头的路由上应用中间件。它将匹配像/profile/123这样的路线。点击这里了解更多关于configmatcher的信息。

最新更新