簡體   English   中英

如何為 next.js 中間件創建動態、受保護的路由

[英]How to create dynamic, protected routes for next.js middleware

我創建了一個文件 routes.ts 來存儲我想要保護的路由。 這適用於常規路由,例如我的“/profile”路由,但是當我嘗試添加動態 url 時,它不起作用(未通過身份驗證的用戶仍然可以查看這些路由)。

路線.ts

export const protectedRoutes = ["/profile", "/profile/[id]", "/timeline/[id]", "/"];
export const authRoutes = ["/login"];
export const publicRoutes = [];

中間件.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的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM