如何在 Next.js 中结合 NextAuth(v5) 和 Next-Intl 中间件(应用程序路由)

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

我正在开发一个 Next.js 应用程序,该应用程序使用 NextAuth(v5) 进行身份验证,使用 Next-Intl 进行国际化。我需要将这些功能无缝地结合起来。这是我迄今为止尝试过的:

当前中间件:

import NextAuth from "next-auth";
import { authConfig } from "src/app/auth.config";

export default NextAuth(authConfig).auth;

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

之前的方法(不适用于 NextAuth v5):

import { withAuth } from 'next-auth/middleware'; // Deprecated in NextAuth v5

// ... (middleware logic using withAuth, not applicable in v5)

https://next-intl-docs.vercel.app/docs/routing/middleware#example-auth-js

说明:

  • NextAuth v5 不再直接使用
    withAuth
    中间件。此方法不适用于当前版本。
next.js next-auth next-intl
1个回答
0
投票

这有效:

中间件.js

import createMiddleware from "next-intl/middleware";
import { NextResponse } from "next/server";

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

export async function middleware(request) {
  let response = NextResponse.next();

  // Exclude specific paths from further processing
  if (
    !request.nextUrl.pathname.startsWith("/login") &&
    !request.nextUrl.pathname.startsWith("/api") &&
    !request.nextUrl.pathname.startsWith("/_next") &&
    !request.nextUrl.pathname.includes(".")
  ) {
    return internationalizationMiddleware(request);
  }
  // Return the response object directly
  return response;
}

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

auth.js

import NextAuth from "next-auth";
import github from "next-auth/providers/github";

export const { auth, handlers, signIn, signOut, update } = NextAuth(() => {
  return {
    secret: process.env.AUTH_SECRET,
    debug: false,
    basePath: "/api/auth",
    providers: [github]
  };
});
© www.soinside.com 2019 - 2024. All rights reserved.