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

如何配置两个Next.js微前端的路由重写并解决失效问题?

Next.js微前端路由跳转无响应问题解决

问题场景

使用两个Next.js 13.5.6 App Router应用搭建微前端架构:

  • main应用监听3000端口,配置重写规则希望将/redirect路由代理到3001端口的redirect应用
  • redirect应用设置了basePath: "/redirect",但点击main页面的Redirect链接无任何反应

核心问题

main应用的重写规则顺序错误,第一个通用规则"/:path*"会匹配所有请求,导致后续针对/redirect的规则根本无法触发。

解决步骤

1. 调整main应用的重写规则顺序

把最具体的路由规则放在最前面,通用规则放到最后,确保/redirect相关请求能被正确匹配:

修改main/next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/redirect/:path*",
        destination: `http://localhost:3001/redirect/:path*`,
      },
      {
        source: "/redirect",
        destination: `http://localhost:3001/redirect`,
      },
      {
        source: "/:path*",
        destination: `/:path*`,
      },
    ];
  },
};

module.exports = nextConfig;

2. 修复redirect应用的返回跳转链接

由于redirect应用配置了basePath: "/redirect",默认的Link href="/"会生成/redirect/路径,点击后仍停留在代理路由。需通过basePath属性关闭basePath影响,直接跳转到main应用根路径:

修改redirect/app/page.tsx:

import Link from "next/link";

export default function Home() {
  return (
    <main>
      <h1>Redirect</h1>
      <Link href="/" basePath={false}>
        <h2>Main</h2>
      </Link>
    </main>
  );
}

3. 验证静态资源加载(可选)

为确认静态资源正常加载,可在两个应用的app/globals.css添加简单样式:

main {
  padding: 2rem;
}
h1 {
  color: #2563eb;
}
h2 {
  cursor: pointer;
  color: #dc2626;
}

验证方式

  1. 在main目录执行npm run dev启动主应用
  2. 在redirect目录执行npm run dev启动子应用
  3. 访问http://localhost:3000,点击Redirect链接,应成功加载redirect应用页面
  4. 在redirect页面点击Main链接,应返回main应用根页面

内容的提问来源于stack exchange,提问作者tnsaturday

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:58:29