Next.js路由中间件与next-intl国际化配置问题求助
问题:Next.js整合next-intl国际化与路由鉴权中间件失败
在Next.js与Laravel环境中,需实现以下需求:当用户没有IncomeController Cookie时,禁止直接输入URL访问受保护页面,同时结合next-intl实现国际化路由。
当前遇到的困境:
- 单独使用next-intl中间件:路由国际化正常,但无法实现路由保护
- 单独使用鉴权中间件:路由保护生效,但国际化功能失效
- 将两者整合后出现错误,无法正常运行
整合后报错的中间件代码
import { NextResponse } from "next/server"; import { isPathStartsWithBackSlash } from "./app/utils/checkUrlTypes"; import createMiddleware from "next-intl/middleware"; const locales = ["en", "mm", "jp"]; const defaultLocale = "mm"; const i18nMiddleware = createMiddleware({ locales, defaultLocale }); export function middleware(request) { const pathName = request.nextUrl.pathname; console.log("pathName", pathName); // Internationalization logic (using next-intl) i18nMiddleware(request); // Execute internationalization middleware first // Authentication logic if (isPathStartsWithBackSlash(pathName)) { const cookies = request.headers.get("cookie"); const hasCookie = cookies && cookies.includes("IncomeController"); if (!hasCookie) { console.log("no cookie"); return NextResponse.redirect(new URL("/404", request.url)); } } // Continue with the default behavior return NextResponse.next(); } export const config = { matcher: ["/", "/(mm|jp|en)/:path*"], };
仅国际化正常但无路由保护的代码
//TODO ADD route middleware for internationalization import createMiddleware from "next-intl/middleware"; import { NextResponse } from "next/server"; let locales = ["en", "mm", "jp"]; const middleware = createMiddleware({ // Add locales you want in the app locales: ["en", "mm", "jp"], // Default locale if no match defaultLocale: "mm", }); export default middleware; export const config = { // Match only internationalized pathnames matcher: ["/", "/(mm|jp|en)/:path*"], };
仅路由保护正常但无国际化的代码
import { NextResponse } from 'next/server'; import { isPathStartsWithBackSlash } from './libs/checkUrlTypes' export function middleware(request) { const pathName = request.nextUrl.pathname // Check if the requested URL matches a protected route if (isPathStartsWithBackSlash(pathName)) { // Check if the cookie exists in the request headers const cookies = request.headers.get('cookie'); const hasCookie = cookies && cookies.includes('IncomeController'); if (!hasCookie) { // If the cookie is not present, redirect to the unauthorized page return NextResponse.redirect(new URL('/404', request.url)); } } // If the request doesn't match a protected route or the user is authenticated, continue with the default behavior return NextResponse.next(); } export const config = { matcher: ['/:path*'], };
(注:已附上Next.js文件夹结构截图与layout.jsx截图)
内容的提问来源于stack exchange,提问作者LwinMoeAung
相关产品推荐
相关产品推荐

