NextJs多租户中间件与Clerk Auth中间件

epggiuax  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(104)

请在最后查看我的错误截图。
内容:
我用Clerk Auth开发了一个NextJs Web应用程序,它工作得很好!我后来决定通过使用Next Multitenancy Template添加多租户,该模板使用中间件来查找域名更改,模板也使用Next Auth。所以,我将以前的Web应用程序与它合并。我将Next Auth留给多租户管理系统,并希望使用Clerk Auth为租户,到目前为止,没有冲突。
现在,我的职员身份验证中间件和多租户中间件发生了冲突。
上一个应用程序目录
x1c 0d1x的数据
合并后的应用程序目录



我从多租户模板的[domain]目录中的原始应用程序中复制了所有应用程序文件,并尽我所知解决了所有依赖性问题,组件,钩子,库。
我的中间件代码:

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

// // Developer Message 2 : This is for Clerk support. To Further Check Proceed To Link : https://clerk.com/docs/quickstarts/nextjs
// // After this (auth) folder was created in app
// //Below is Developer Message 3

import { authMiddleware } from "@clerk/nextjs";
 
// This example protects all routes including api/trpc routes
// Please edit this to allow other routes to be public as needed.
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your middleware

export default authMiddleware({

      // Developer Message 3
      //Public Routes Enable Unauthorised users to visit below mentioned routes 

      publicRoutes: ["/","/api/webhook"]

});


export const config = {
  matcher: [
    /*
     * Match all paths except for:
     * 1. /api routes
     * 2. /_next (Next.js internals)
     * 3. /_static (inside /public)
     * 4. all root files inside /public (e.g. /favicon.ico)
     */
    '/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)',  // from clerk auth
    "/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)", //from multitenancy template
  ],
};

export async function middleware(req: NextRequest) {
  const url = req.nextUrl;

  // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
  const hostname = req.headers
    .get("host")!
    .replace(".localhost:3000", `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);

  const searchParams = req.nextUrl.searchParams.toString();
  // Get the pathname of the request (e.g. /, /about, /blog/first-post)
  const path = `${url.pathname}${
    searchParams.length > 0 ? `?${searchParams}` : ""
  }`;

  // rewrites for app pages
  if (hostname == `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
    const session = await getToken({ req });
    if (!session && path !== "/login") {
      return NextResponse.redirect(new URL("/login", req.url));
    } else if (session && path == "/login") {
      return NextResponse.redirect(new URL("/", req.url));
    }
    return NextResponse.rewrite(
      new URL(`/app${path === "/" ? "" : path}`, req.url),
    );
  }

  // special case for `vercel.pub` domain
  if (hostname === "vercel.pub") {
    return NextResponse.redirect(
      "https://vercel.com/blog/platforms-starter-kit",
    );
  }

  // rewrite root application to `/home` folder
  if (
    hostname === "localhost:3000" ||
    hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
  ) {
    return NextResponse.rewrite(
      new URL(`/home${path === "/" ? "" : path}`, req.url),
    );
  }

  // rewrite everything else to `/[domain]/[slug] dynamic route
  return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));
}

字符串
我将两个中间件代码放在同一个文件夹中,但是两个默认值不能共存,所以我尝试在不使用default关键字的情况下导出multitenancy middleware(),它似乎工作了。
我添加了标签来封装html标签,这样认证就可以在整个应用程序上工作。我还尝试将标签放置在[domain]目录应用程序布局中,使其只对租户有效,但错误并没有消失。
每当我通过职员身份验证登录,我应该降落在 Jmeter 板上,然后发生以下错误




我认为是我的中间件导致了这个问题,我已经没有办法了。

1yjd4xko

1yjd4xko1#

我做了这样的事情,它的工作

import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
import { NextResponse } from "next/server";

// This example protects all routes including api/trpc routes
// Please edit this to allow other routes to be public as needed.
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware
export default authMiddleware({
  publicRoutes: ["/"],
  afterAuth: (auth, req) => {
    const url = req.nextUrl;

    // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3123)
    // biome-ignore lint/style/noNonNullAssertion: <explanation>
    let hostname = req.headers.get("host")!.replace(".localhost:3123", `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);

    // special case for Vercel preview deployment URLs
    if (hostname.includes("---") && hostname.endsWith(`.${process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX}`)) {
      hostname = `${hostname.split("---")[0]}.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`;
    }

    const searchParams = req.nextUrl.searchParams.toString();
    // Get the pathname of the request (e.g. /, /about, /blog/first-post)
    const path = `${url.pathname}${searchParams.length > 0 ? `?${searchParams}` : ""}`;

    // rewrites for app pages
    if (hostname === `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
      if (!auth.userId && !auth.isPublicRoute) {
        const prefix = process.env.NODE_ENV === "development" ? "http://" : "https://";
        return redirectToSignIn({ returnBackUrl: `${prefix}${hostname}/` });
      }

      return NextResponse.rewrite(new URL(`/app${path === "/" ? "" : path}`, req.url));
    }

    // special case for `vercel.pub` domain
    //   if (hostname === 'vercel.pub') {
    //     return NextResponse.redirect(
    //       'https://vercel.com/blog/platforms-starter-kit',
    //     );
    //   }

    // rewrite root application to `/home` folder
    if (hostname === "localhost:3123" || hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN) {
      return NextResponse.rewrite(new URL(`/home${path === "/" ? "" : path}`, req.url));
    }
    // console.log("here");

    // rewrite everything else to `/[domain]/[slug] dynamic route
    return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));
  },
});

export const config = {
  matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};

字符串

相关问题