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'
    }
}
相关推荐
志尊宝34 分钟前
AI原生前端开发(042):AI辅助的路由设计与优化
javascript·react.js·ai-native
znsoft18 小时前
MaClaw(码卡龙)技术拆解:一个 Go + React 的可自进化智能体平台
开发语言·react.js·golang
濮水大叔21 小时前
React/Next.js 生态里,有没有 CabloyJS 这样的全栈框架?
react.js·全栈·next.js
前端小D1 天前
React Native Android 项目搭建
android·react native·react.js
Highcharts.js2 天前
Highcharts 集成到 React 或 Vue 项目中时,如何高效地使用 TypeScript技巧?
vue.js·人工智能·react.js·typescript·前端框架·highcharts
liuchangng3 天前
React 19 + Vite 6 实战:从教材 PDF 到 866 词间隔重复单词 App
前端·react.js·pdf·vite·开源项目
鸿蒙开发4 天前
Three.js 首帧卡顿排查:compileAsync 之后,为什么还会停一下?
react.js·three.js
小李科技4 天前
【性能优化】事件委托:目标定位与 React/Vue 实战
前端·vue.js·react.js·面试·性能优化·前端框架
csj504 天前
前端基础之《React(16)—Modal组件封装》
前端·react.js
ZoeLandia6 天前
React11:数据请求与 TanStack Query
前端·react.js·typescript·react