在 Next Js 中链接多个中间件的正确方法是什么

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

哦,我很困惑我应该如何在下一个 js 中链接多个中间件。假设我有两个页面 /dashboard 和 /admin ,它们都存在于 pages 目录中。在 /dashboard 中,我想检查用户是否经过身份验证,而在 admin 中,我想检查用户是否具有管理员角色。

所以根据文档,我想在 src 目录(也与 pages 目录同一级别)中创建一个 middleware.js 文件

以下是我的代码

import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";

async function isAuth(req) {
  const token = await getToken({ req });
  if (token === null) {
    return false;
  }
  return token;
}

async function isAdmin(token) {
  const { role } = token;
  return role === "admin" ? true : false;
}

function redirectToHomePage(req) {
  const url = req.nextUrl.clone();
  url.pathname = "/";
  return NextResponse.redirect(url);
}

export async function middleware(req) {
  const res = NextResponse.next();
  const path = req.nextUrl.pathname;
  if (
    req.nextUrl.pathname.startsWith("/random") ||
    req.nextUrl.pathname.startsWith("/admin")
  ) {
    //check if you are authenticated
    const token = await isAuth(req);
    if (token) {
        //check if you are admin
      const admin = await isAdmin(token);
      return admin
        ? res
        : new NextResponse(
            JSON.stringify({ success: false, message: "You are not an admin" }),
            { status: 401, headers: { "content-type": "application/json" } }
          );
    }
    return redirectToHomePage(req);
  }
  if (path === "/dashboard") {
    const result = await isAuth(req);
    if (result) {
      return res;
    }
    return redirectToHomePage(req);
  }
  return res;
}

以下代码确实有效并得到了我想要的东西,但是当代码库变大时,我很快就会看到它变得非常混乱。

所以我的问题是这是正确的方法还是有更好的方法?

谢谢。

next.js middleware
© www.soinside.com 2019 - 2024. All rights reserved.