将 next-intl 提供的中间件与预先存在的中间件集成

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

我有一个现有的中间件来处理身份验证。

现在我正在尝试将 next-intl 添加到我的项目中。然而我很难将它们两者结合起来。

我按照他们的教程并按照文档所述实现了所有内容: https://next-intl.dev/docs/getting-started/app-router/with-i18n-routing

我正在使用 Next.JS 15 App Router 和 Src 目录

这是我现有的中间件:

import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth/iron-session";

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const session = await getSession();
  const isLoggedIn = session.isLoggedIn;

  // Check if the user is logged in
  if (!isLoggedIn && pathname !== "/einloggen") {
    return NextResponse.redirect(new URL("/einloggen", request.url));
  }
  if (isLoggedIn && pathname === "/einloggen") {
    return NextResponse.redirect(new URL("/", request.url));
  }

  // Allow access to other pages
  return NextResponse.next();
}

export const config = {
  // Apply the middleware to all paths except for the ones we want to exclude (like _next and favicon.ico)
  matcher: ["/((?!_next|favicon.ico).*)"],
};
next.js middleware next-intl
1个回答
0
投票

出现冲突是因为 auth 中间件和 next-intl 中间件都必须一个接一个地处理请求,这可能会导致一些路径处理问题。

import { NextRequest, NextResponse } from "next/server";
import { createMiddleware } from "next-intl/middleware";
import { getSession } from "@/lib/auth/iron-session";

// Initialize next-intl middleware
const nextIntlMiddleware = createMiddleware({
  locales: ["en", "de"], // Add supported locales
  defaultLocale: "en",
});

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Run next-intl middleware for locale detection
  const intlResponse = nextIntlMiddleware(request);
  if (intlResponse) return intlResponse;

  // Run authentication logic
  const session = await getSession();
  const isLoggedIn = session?.isLoggedIn;

  if (!isLoggedIn && pathname !== "/einloggen") {
    return NextResponse.redirect(new URL("/einloggen", request.url));
  }

  if (isLoggedIn && pathname === "/einloggen") {
    return NextResponse.redirect(new URL("/", request.url));
  }

  return NextResponse.next();
}

// Middleware matcher configuration
export const config = {
  matcher: [
    "/((?!_next|favicon.ico).*)" // Exclude _next and favicon.ico paths
  ],
};
© www.soinside.com 2019 - 2024. All rights reserved.