Module Federation + Next.js + Tanstack Query:SSR 数据获取的跨应用集成实战(nextjs-ssr-react-query 示例深度剖析)
Module Federation + Next.js + Tanstack Query:SSR 数据获取的跨应用集成实战(nextjs-ssr-react-query 示例深度剖析)
本文以 module-federation-examples 仓库中的 nextjs-ssr-react-query 示例 为核心,完整剖析如何将 Module Federation 的跨应用组件共享能力与 Next.js 的服务端数据获取策略(SSR、ISR)以及 Tanstack Query(react-query)的缓存/水合机制三者打通。读完本文,你将掌握
@module-federation/nextjs-mq在 SSR 场景下 remoteEntry 双入口的配置方法、dehydrate/Hydrate跨应用共享数据状态的完整链路,以及 host 应用代理 remote 页面getServerSideProps的高级用法。
一、示例定位:一个「进阶」的 Next.js 微前端数据获取案例
该示例由 Module Federation 官方团队维护,在仓库中被明确标注为 advanced example(进阶示例):它不只是把几个 React 组件暴露给其他应用消费,而是同时解决了两个难题——在 SSR 场景下正确加载远程组件,以及让跨应用共享的服务端数据通过 Tanstack Query 无缝水合到客户端。
示例基于 Nx 17 workspace 组织,根配置见 package.json 与 nx.json,核心依赖版本如下(以仓库实际锁定版本为准):
| 依赖 | 版本 | 用途 |
|---|---|---|
@module-federation/nextjs-mf |
8.8.56 | 为 Next.js 提供 Module Federation 能力(NextFederationPlugin) |
next |
14.2.13 | 应用框架 |
@tanstack/react-query |
^4.42.0 | 数据获取与缓存 |
react / react-dom |
18.3.1 | 视图层 |
styled-components |
5.3.11 | 样式方案(跨应用共享) |
nextjs-cors |
^2.2.1 | API 路由跨域处理 |
整个示例由 4 个 Next.js 应用组成,端口映射定义在各应用的 project.json 的 serve.targets.options.port 中:
| 应用 | 端口 | 角色 | 说明 |
|---|---|---|---|
host |
3000 | 主 host(advanced federation) | 组合消费 plp / header / button 三个 remote |
plp |
3001 | remote(advanced federation) | 商品列表页(Product List Page),暴露页面与组件,同时消费 button |
header |
3002 | remote(basic federation) | 仅暴露 Header 组件 |
button |
3003 | remote(basic federation) | 仅暴露 Button 组件 |
其中 host 与 plp 形成了「双向消费」的 advanced 关系:host 消费 plp 暴露的页面,plp 内部又消费 button 暴露的按钮组件;而 header、button 仅做单一组件暴露,属于 basic federation。
二、快速启动与验证
原文档给出的启动流程只有两步命令,但可以进一步拆解以便理解每一步的作用:
# 1. 安装依赖(在 nextjs-ssr-react-query 目录下执行)
yarn install
# 2. 并行启动全部 4 个 Next.js 应用
nx run-many --target=serve --all --skip-nx-cache --verbose --parallel=4
命令参数说明:
--target=serve:执行所有项目(project)中名为serve的 target,即各应用 project.json 中由@nrwl/next:serverexecutor 定义的开发服务;--all:对 workspace 内所有项目生效;--skip-nx-cache:跳过 Nx 缓存,强制重新执行(示例是热更新场景,避免陈旧产物干扰);--parallel=4:并行度 4,与 4 个应用一一对应;--verbose:输出详细日志,便于排查启动问题。
启动后按原文档说明访问:
- http://localhost:3000/ —— 主 host 应用(advanced federation),页面组合了 Header、Button 与 plp 的商品列表;
- http://localhost:3001/ —— plp 应用(advanced federation),独立商品列表页;
- http://localhost:3002/ —— header 应用(basic federation);
- http://localhost:3003/ —— button 应用(basic federation)。
提示:由于 4 个应用之间存在消费关系(host → plp → button),启动顺序上应先保证 remote 就绪;使用上述
run-many并行命令时,NextFederationPlugin在开发模式下会通过轮询/异步加载机制处理 remote 未就绪的情况,浏览器端通常会自动恢复。
三、NextFederationPlugin 配置:SSR 场景下的关键差异
3.1 remote 声明:服务端与客户端各有一套 remoteEntry
这是整个示例中 SSR 与 Module Federation 结合最核心的一行逻辑,位于 host/next.config.js:
// this enables you to use import() and the webpack parser
// loading remotes on demand, not ideal for SSR
const remotes = isServer => {
const location = isServer ? 'ssr' : 'chunks';
return {
plp: `plp@${PLP_APP_URL}/_next/static/${location}/remoteEntry.js`,
header: `header@${HEADER_APP_URL}/_next/static/${location}/remoteEntry.js`,
button: `button@${BUTTON_APP_URL}/_next/static/${location}/remoteEntry.js`,
};
};
要点拆解:
@module-federation/nextjs-mf在构建 Next.js 应用时,会为 服务端(SSR)与浏览器端各产出一份 remoteEntry:分别位于/_next/static/ssr/remoteEntry.js与/_next/static/chunks/remoteEntry.js;- 因此配置里必须通过
webpack(config, { isServer })回调拿到isServer标志,动态拼接 remote 地址:服务端渲染时拉取ssr目录下的入口,浏览器端拉取chunks目录下的入口; - 各 remote 的 base URL 由环境变量控制(详见下文第六节),默认值即上表中的三个 localhost 地址。
各 remote 应用自身的 filename 统一设置为 'static/chunks/remoteEntry.js',例如 plp/next.config.js 中的插件实例:
new NextFederationPlugin({
name: 'plp',
filename: 'static/chunks/remoteEntry.js',
remotes: remotes(isServer),
extraOptions: {
automaticAsyncBoundary: true,
},
exposes: {
'./ProductsPage': './pages/index.tsx',
'./ProductList': './components/ProductList/index.tsx',
'./ProductCard': './components/ProductCard/index.tsx',
},
shared: {
'@tanstack/react-query': {
requiredVersion: false,
singleton: true,
},
'@tanstack/query-core': {
requiredVersion: false,
singleton: true,
},
'styled-components': {
eager: true,
singleton: true,
requiredVersion: dependencies['styled-components'],
},
},
}),
3.2 exposes 与 shared 的配置语义
- exposes:plp 将「页面(
./pages/index.tsx)、列表组件、卡片组件」三样东西暴露出去,供 host 消费;header 只暴露./Header(见 header/next.config.js),button 只暴露./Button(见 button/next.config.js),这就是 basic 与 advanced 在暴露面复杂度上的直观差别。 - shared(共享依赖):这是跨应用数据打通的关键——
@tanstack/react-query与@tanstack/query-core都以singleton: true共享,requiredVersion: false表示不强制校验版本,保证所有应用拿到的是同一个 QueryClient 内核实例,这是后续Hydrate能跨应用工作的前提;styled-components配置了eager: true(同步加载,避免样式闪烁)+singleton: true+ 严格版本(取根 package.json 中声明的dependencies版本)。
- automaticAsyncBoundary:
extraOptions.automaticAsyncBoundary: true让@module-federation/nextjs-mf自动为远程组件包一层异步边界,避免「未就绪时直接渲染远程组件」导致的水合错误。
3.3 host 的 consumption 侧配置差异
host 的插件配置(host/next.config.js)与 plp 几乎对称,区别在于 exposes: {}(不对外暴露任何模块),只声明了三个 remote。这体现了 Module Federation 的灵活性:同一个应用既可以同时是 host 与 remote,也可以只做其一,取决于你写不写 exposes/remotes。
四、Tanstack Query 与 SSR 集成:从服务端预取到客户端水合
4.1 全局 QueryClient 与 Provider
每个 Next.js 应用在 services/queryClient.ts 中创建一个单例 QueryClient,然后在 _app.tsx 中挂载 Provider 与 Hydrate 组件(host 与 plp 的实现一致,见 host/pages/_app.tsx):
import { Hydrate, QueryClientProvider } from '@tanstack/react-query';
import { queryClient } from '../services/queryClient';
function CustomApp({ Component, pageProps }: AppProps) {
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
);
}
QueryClientProvider向下提供统一的 query 实例;<Hydrate state={pageProps.dehydratedState}>把服务端序列化下来的数据「水合」进客户端缓存,页面首屏无需二次请求即可直接渲染已有数据。
4.2 服务端预取:getServerSideProps + prefetchQuery + dehydrate
以 plp 首页 apps/plp/pages/index.tsx 为例,这是「SSR 每次请求动态预取」的典型写法:
export async function getServerSideProps({ query }: GetServerSidePropsContext) {
const queryClient = new QueryClient();
const limit = query?.limit ? +query.limit : 10;
const skip = query?.skip ? +query.skip : 0;
const products = await fetchProducts({ limit, skip });
await queryClient.prefetchQuery(['products', limit, skip], () => products, {
initialData: products,
staleTime: 5000, // data will be considered stale after 5 seconds
});
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
关键点:
- 服务端每次请求都新建独立的
QueryClient(而不是复用全局单例),避免跨请求污染缓存; prefetchQuery使用['products', limit, skip]作为查询键,staleTime: 5000表示该数据在 5 秒内视为新鲜,客户端在 5 秒内重复请求同一查询键时不会发起新的网络请求;dehydrate(queryClient)将服务端缓存序列化为纯 JSON 传给pageProps.dehydratedState。
4.3 客户端消费:useQuery 与「不直接读取 props」
页面对应组件 apps/plp/components/ProductList/index.tsx 使用 useQuery 消费同一查询键:
const { data: products, isLoading } = useQuery(
['products', limit, skip],
() => fetchProducts({ limit, skip }),
{
initialData: [],
},
);
注意 plp 页面代码中的注释(apps/plp/pages/index.tsx):products 数据并不直接从 page props 读取,而是依赖 Hydrate 从 dehydratedState 恢复缓存后由 useQuery 命中。这正是 Tanstack Query 的推荐模式:组件只关心自己的 query 声明,数据来源对组件透明。initialData: [] 则保证了在服务端数据尚未水合完成的极端情况下也有兜底渲染。
4.4 进阶用法:host 代理 remote 页面的 getServerSideProps
本示例最「advanced」的地方在 host 首页 host/pages/index.tsx:host 的服务端数据预取逻辑直接复用 remote 页面导出的同名方法:
export async function getServerSideProps(context: GetServerSidePropsContext) {
const page = await import('plp/ProductsPage');
if (page.getServerSideProps) {
return page.getServerSideProps(context);
}
return {
props: {},
};
}
原理与价值:
- 在服务端(Node 运行时)通过
import('plp/ProductsPage')动态加载 remote 模块(此路径即第三小节中isServer ? 'ssr'分支对应的产物); - 若 remote 页面导出了
getServerSideProps,则原样调用并把结果透传,从而让 host 首屏的 HTML 直接包含由 plp 预取的dehydratedState——用户在 host 页面看到商品列表时,数据已经在服务端拿到并序列化进 HTML; - 页面组件本身则通过
next/dynamic加载三个 remote 并保持ssr: true(host/pages/index.tsx),保证远程组件也参与 SSR 渲染。
五、静态生成与增量再生(ISR):getStaticProps 变体
除了 SSR,示例还演示了把同一套 prefetch + dehydrate 模式迁移到静态生成(SSG/ISR)上,位于商品详情页 apps/plp/pages/products/[productId].tsx:
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
};
}
export async function getStaticProps({ params }: GetStaticPropsContext) {
const queryClient = new QueryClient();
const { productId } = params;
await queryClient.prefetchQuery(
['product', productId],
() => fetchProductById(productId as string),
{
staleTime: 5000,
},
);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
revalidate: 60 * 60, // will revalidate the page every hour
};
}
getStaticPaths返回空paths+fallback: 'blocking':首访时按需在服务端生成页面(阻塞式等待),后续访问走静态缓存;getStaticProps内同样先prefetchQuery(['product', productId], ...)再dehydrate;revalidate: 60 * 60表示每小时后台重新生成一次页面,即标准的 ISR(Incremental Static Regeneration)策略。
对应的客户端组件 apps/plp/components/ProductOverview/index.tsx 用 useQuery(['product', productId], ...) 读取,并区分 isLoading / isFetching 两种状态给出「loading...」与「product not found」的兜底 UI。
六、数据源与 API 路由:跨域代理与环境变量
6.1 数据源
示例数据来自公开的 dummyjson.com 商品 API(https://dummyjson.com/products),是一个无需鉴权的 REST 接口,便于演示「服务端取数 → 序列化 → 水合」全链路。
6.2 通过 Next.js API 路由做代理
直接让浏览器跨域请求 dummyjson.com 会遇到 CORS 问题,因此 plp 提供了两个 API 路由做服务端代理,并借助 nextjs-cors 放行跨域:
- 列表接口 apps/plp/pages/api/products/index.ts:接收
skip/limit查询参数,转发到https://dummyjson.com/products?limit=...&skip=...,并在响应前执行cors(req, res, { methods: [...], origin: '*' }); - 详情接口 apps/plp/pages/api/products/[productId].ts:转发到
https://dummyjson.com/products/${productId},上游 404 时返回{ message: "Product with id '...' not found" }。
这样无论是服务端 fetchProducts / fetchProductById,还是浏览器端后续的 useQuery 请求,都统一走 NEXT_PUBLIC_PLP_URL 指向的本地代理,天然规避跨域。
6.3 环境变量一览
以 host/next.config.js 与 apps/plp/components/ProductList/index.tsx 中实际使用到的为准:
| 环境变量 | 默认值 | 用途 |
|---|---|---|
NEXT_PUBLIC_PLP_APP_URL |
http://localhost:3001 |
host 声明 plp remote 的地址 |
NEXT_PUBLIC_HEADER_APP_URL |
http://localhost:3002 |
host 声明 header remote 的地址 |
NEXT_PUBLIC_BUTTON_APP_URL |
http://localhost:3003 |
host/plp 声明 button remote 的地址 |
NEXT_PUBLIC_PLP_URL |
未设默认,需显式配置 | 客户端组件拼接 API 代理地址(如 http://localhost:3001) |
此外 next.config.js 的 images.domains 配置了 dummyjson.com / i.dummyjson.com,用于放行商品缩略图的远程图片加载(组件中通过 next/image 渲染,见 ProductCard/index.tsx)。
七、跨应用组件消费链路与共享类型
7.1 host 的组合视图
host 首页把三个 remote 组件组合在一个 styled 容器里(host/pages/index.tsx):Header 内嵌 Button,下方渲染 PlpProductsPage(传入 color="forestgreen" 定制虚线边框颜色)。而 plp 的 ProductCard 内部又动态消费了 button/Button(apps/plp/components/ProductCard/index.tsx),形成「host → plp → button」的嵌套消费链——这正是 advanced federation 的典型形态。
7.2 共享类型库
跨应用的数据结构类型被抽到 libs/domain/src/types.ts,定义 Product、Cursor(limit/skip 分页游标)、PaginatedReponse<T, Key> 泛型响应,并经 libs/domain/src/index.ts 统一导出,别名 @acme/domain 在 tsconfig.base.json 的 paths 中映射。所有应用通过 import { Product } from '@acme/domain' 引用同一份类型,避免远程模块间类型漂移。
八、测试验证
每个应用都带有基于 @testing-library/react 的冒烟测试,例如 apps/plp/specs/index.spec.tsx:
import { render } from '@testing-library/react';
import Index from '../pages/index';
describe('Index', () => {
it('should render successfully', () => {
const { baseElement } = render(<Index />);
expect(baseElement).toBeTruthy();
});
});
对应应用的 project.json 中配置了 test target(@nrwl/jest:jest),可用 nx test plp 等命令按需运行。
九、注意事项与适用前提
- Next.js 支持状态:示例 README 顶部明确提示「Support For Next.js is ending」(对 Next.js 的支持即将结束),相关进展记录在 module-federation/core 仓库的 issue #3153 中。本文所有配置基于仓库锁定的 Next.js 14.2.13 与
@module-federation/nextjs-mf8.8.56,在规划生产使用时务必评估该演进方向。 - remoteEntry 双入口是硬性要求:SSR 场景下必须像第三小节那样按
isServer区分ssr/chunks目录,否则服务端或客户端必然有一侧加载失败。 - shared 的 singleton 语义:
@tanstack/react-query与@tanstack/query-core必须保持singleton: true,这是dehydrate/Hydrate跨应用生效的前提;若两侧实例化各自的内核,水合将失效。 - 服务端每次请求新建 QueryClient:不要复用全局单例做 SSR 预取,否则数据会在请求间串扰(示例中所有
getServerSideProps/getStaticProps均遵循此规则)。 - 环境变量需按部署环境注入:四个 remote 地址与 API 代理地址默认指向 localhost,多机部署或容器化时必须显式设置,示例本身未附带
.env文件。
十、可继续深入阅读的仓库文件
- 示例总入口:nextjs-ssr-react-query/README.md
- 根依赖与版本锁定:nextjs-ssr-react-query/package.json
- 构建编排:nextjs-ssr-react-query/nx.json
- 四个应用的联邦配置:host、plp、header、button
- SSR 预取实现:plp 首页、host 代理
- ISR 实现:商品详情页
- API 代理:列表接口、详情接口
- 共享类型:libs/domain/src/types.ts
该示例完整回答了「微前端架构下,服务端数据到底由谁取、怎么跨应用共享」这一核心问题:remote 负责取数与序列化,host 通过代理 getServerSideProps 保持服务端渲染完整性,Tanstack Query 的 dehydrate/Hydrate 负责把数据无损地交还给各自应用内的 useQuery 消费者,是学习 Next.js SSR + Module Federation 组合拳不可多得的参考实现。