You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在已启用Locale的Next.js应用中集成Nextra Docs(含Middleware)

Next.js 集成 Nextra Docs 实现带语言前缀的 Docs 路径解决方案

1. 基础配置与 Nextra 安装

先安装依赖:

npm install nextra nextra-theme-docs

在项目根目录创建 docs 文件夹,存放你的文档内容(比如 docs/index.mdx、docs/guide.mdx 等),同时创建 theme.config.tsx 用于自定义 Nextra 主题。

2. 动态路由承载 Nextra,规避 pages 下的语言目录

创建 pages/[locale]/docs/[[...slug]].tsx 动态路由文件,作为 Nextra 的入口,同时处理语言参数的校验:

import { useRouter } from 'next/router'
import Nextra from 'nextra'
import theme from 'nextra-theme-docs'
import 'nextra-theme-docs/style.css'

const Docs = ({ locale }) => {
  const router = useRouter()
  // 初始化 Nextra,指定当前语言下的 Docs 基础路径
  const NextraComponent = Nextra({
    theme,
    themeConfig: './theme.config.tsx',
    basePath: `/${locale}/docs`,
  })

  return <NextraComponent {...router.query} />
}

export async function getServerSideProps(context) {
  const { locale } = context.params
  // 校验语言参数是否合法,非法则重定向到默认语言
  const allowedLocales = ['en', 'zh'] // 替换为你的实际语言列表
  if (!allowedLocales.includes(locale)) {
    return {
      redirect: {
        destination: `/en/docs`,
        permanent: false,
      },
    }
  }

  return { props: { locale } }
}

export default Docs

3. 自定义 Nextra 面包屑,隐藏语言前缀

修改 theme.config.tsx,自定义面包屑组件,过滤掉语言前缀的显示:

import { DocsThemeConfig } from 'nextra-theme-docs'

const config: DocsThemeConfig = {
  // 保留你的其他主题配置(比如导航、页脚等)
  breadcrumb: ({ items }) => {
    return items.map(item => {
      // 移除面包屑中语言前缀的项,或修改显示文本
      if (item.href.match(/^\/[a-z]{2}\/docs/)) {
        // 只保留文档路径部分,去掉语言前缀
        const cleanHref = item.href.replace(/^\/[a-z]{2}\/docs/, '/docs')
        // 如果是语言对应的根节点,直接隐藏;否则保留文档标签
        const cleanLabel = item.label === item.href.split('/')[1] ? '' : item.label
        return { ...item, href: cleanHref, label: cleanLabel }
      }
      return item
    }).filter(item => item.label) // 过滤掉空标签的项
  },
}

export default config

4. Middleware 适配,确保路径重定向正确

在你的现有 Middleware 中添加对 Docs 路径的处理,确保无语言前缀的 Docs 请求被重定向到带默认语言的路径:

import { NextResponse } from 'next/server'

export function middleware(request) {
  const { pathname } = request.nextUrl

  // 处理无语言前缀的/docs请求,重定向到默认语言版本
  if (pathname.startsWith('/docs') && !pathname.match(/^\/[a-z]{2}\//)) {
    const defaultLocale = 'en' // 替换为你的默认语言
    return NextResponse.redirect(new URL(`/${defaultLocale}${pathname}`, request.url))
  }

  // 保留你原有的 Middleware 逻辑(比如语言检测、路由保护等)
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}

5. 验证效果

  • 访问 http://localhost:3000/en/docs 可正常加载 Nextra 文档
  • 文档面包屑中不会显示 en 等语言前缀,仅展示文档层级结构

内容的提问来源于stack exchange,提问作者Pankaj Kumar Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:37:34