使用 Nextjs 13 的中间件

问题描述 投票:0回答:1

我正在使用 Nextjs 13 应用程序目录。

我试图添加一个中间件,将未经身份验证的用户重定向到

/login
页面。

但我也想在经过身份验证的用户尝试访问

/login
页面时重定向他们

export async function middleware(request: NextRequest) {
    const verified = //Verification

    if (verified) {
        const requestHeaders = new Headers(request.headers);
        return NextResponse.next({
            request: {
                headers: requestHeaders,
            },
        })
    } else {
        url.pathname = '/login';
        return NextResponse.redirect(url);
    }
}

export const config = {
    matcher: [
        "/",
    ],
};

有没有办法使用中间件来做到这一点。

authentication next.js middleware nextjs13
1个回答
0
投票

您需要一个配置

matcher
来配置您希望中间件运行的所有路径,以及一组精心组合在一起的
if
语句,例如:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const authPahts = ["/login", "/signup", "reset"];

export async function middleware(request: NextRequest) {
  const verified = true; // Update your condition here
  if (verified) {
    console.log(request.nextUrl.pathname);
    if (authPahts.includes(request.nextUrl.pathname)) {
      return NextResponse.redirect(new URL("/", request.url));
    }
    const requestHeaders = new Headers(request.headers);
    return NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    });
  } else {
    if (authPahts.includes(request.nextUrl.pathname)) {
      return NextResponse.next();
    }
    return NextResponse.redirect(new URL("/login", request.url));
  }
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};
© www.soinside.com 2019 - 2024. All rights reserved.