NEXT.js 中间件 NextResponse.redirect 无效

原代码

javascript 复制代码
// src/middleware.js
import { NextResponse } from 'next/server'

export function middleware(request) {
    handleLocale(request)
}

// 处理国际化
const handleLocale = (request) => {
    const locales = ['zh_CN', 'en_US', 'ja_JP']
    const { pathname } = request.nextUrl
    const pathnameHasLocale = locales.some(locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`)

    // 正确进入到匹配语言的目录,不做处理
    if (pathnameHasLocale) {
        // ...
    }
    // 没有进入到匹配的语言目录,设置默认语言,重定向到对应的语言目录
    else {
        const locale = locales[0]
        request.nextUrl.pathname = `/${locale}${pathname}`
        return NextResponse.redirect(request.nextUrl)
    }
}

export const config = {
    // 中间件运行的路径
    matcher: [
        // NEXT.js内部资源路径 /_next
        // e.g. /_next/static/chunks/webpack.js |  /_next/static/chunks/main-app.js |  /_next/static/chunks/app-pages-internals.js
        // 不匹配内部资源,内容资源不需要国际化
        '/((?!_next|favicon.ico).*)',
    ],
}

修改后

NextResponse.redirect 必须要在middleware 方法里执行,不然不生效

javascript 复制代码
// src/middleware.js
export function middleware(request) {
    const localeStatus = handleLocale(request);
    if (localeStatus === 'locale redirect') {
        return NextResponse.redirect(request.nextUrl)
    }
}

// 是否包含国际化的资源路径
const handleLocale = (request) => {
    const locales = ['zh_CN', 'en_US', 'ja_JP']
    const { pathname } = request.nextUrl
    const pathnameHasLocale = locales.some(locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`)

    // 正确进入到匹配语言的目录,不做处理
    if (pathnameHasLocale) {
        return 'locale matched'
    }
    // 没有进入到匹配的语言目录,设置默认语言,重定向到对应的语言目录
    else {
        const locale = locales[0]
        request.nextUrl.pathname = `/${locale}${pathname}`
        return 'locale redirect'
    }
}
相关推荐
song5019 小时前
React Native for OpenHarmony 实战:三方库 react-native-parallax-scroll-view 的鸿蒙化适配指南
分布式·react native·react.js·transformer·harmonyos
song50111 小时前
React Native for OpenHarmony 实战:三方库 react-native-ratings 的鸿蒙化适配指南
javascript·react native·react.js·分类·harmonyos
晓得迷路了16 小时前
栗子前端技术周刊第 149 期 - Vite+ 1.0、Preact 11、Next.js 16.4...
前端·javascript·react.js
song50116 小时前
React Native for OpenHarmony 实战:三方库 react-native-popup-menu 的鸿蒙化适配指南
css·深度学习·react native·react.js·transformer·harmonyos
haluhalu.16 小时前
Agent = LLM + 上下文 + 工具(含观察 / 动作空间、ReAct 循环)
前端·javascript·人工智能·python·react.js·机器学习·个人开发
weixin_448119941 天前
Datawhale Easy Data × AI:构建知识与记忆驱动的 Agent笔记8
人工智能·笔记·react.js
EatFan1 天前
React 项目踩坑实录:useEffect 闭包陷阱、Context 性能陷阱与 React 18 升级避坑排查手册
前端·javascript·react.js·react·react hooks·useeffect·闭包陷阱
梦想的颜色1 天前
【编程实战】AI 时代 APP 开发全栈硬核指南:技术选型 + AI 架构 + 模型落地全维度决策
python·flutter·react native·react.js·ai·桌面应用·milvus
知野小兔1 天前
对比react钩子函数
react.js
阿狗童鞋2 天前
React实战指南
前端·react.js·前端框架