next. js中的多个中间件next. js中的多个中间件

ckx4rj1h  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(137)

我的文件结构:app -> [locale] ->(admin)[dashboard] page.js -(shop)page.js
我想使用职员只为 Jmeter 板及其子页面和下一个intl的所有网页。我在clerk docs中发现了以下代码,但它将身份验证应用于所有页面。

import { authMiddleware } from "@clerk/nextjs";
import createMiddleware from "next-intl/middleware";

const intlMiddleware = createMiddleware({
  locales: ["en", "fa"],
  defaultLocale: "fa",
});

export default authMiddleware({
  beforeAuth: (req) => {
    return intlMiddleware(req);
  },

  publicRoutes: ["/", "/:locale/sign-in"],
});

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

我尝试使用这个way,但我不明白如何将这两个解决方案合并在一起

bz4sfanl

bz4sfanl1#

我也遇到了类似的问题,最后来到了这里。我认为下面的解决方案是正确的。
在我的例子中,我试图在缺少locale的情况下将其添加到路径中,但同时也保护大多数路由-这看起来可能与您正在做的类似。我使用了afterAuth和publicRoutes:

export default authMiddleware({
  afterAuth: (auth, req, evt) => {
    if (auth.userId || auth.isPublicRoute) {
      return localeMiddleware(req);
    }
    // redirect unauthenticated users to about, but keep the locale
    // if there is one
    const locale = getLocaleOrDefault(req)
    req.nextUrl.pathname = `/${locale}/about`
    return Response.redirect(req.nextUrl) 
  },
  publicRoutes: [
    "/en/about",
    "/es/about",
    "/about/"
  ]
});

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

我对nextjs / clerk很陌生,所以这可能不是最好的方法。

相关问题