A minimal monorepo to observe federated-stats.json generation and flushChunks working end-to-end with @module-federation/nextjs-mf.
Built and debugged live to document what actually happens in 8.x — including the bugs we found along the way.
mf-flush-demo/
├── host/ ← Next.js app on :3000 (consumes remotes, does SSR)
│ └── src/pages/
│ ├── _document.js ← where flushChunks() is called
│ ├── _app.js
│ ├── index.js ← SSR-renders Button and UserCard from remote
│ └── debug.js ← fetches and displays federated-stats.json inline
│
├── remote/ ← Next.js app on :3001 (exposes components)
│ └── src/
│ ├── components/
│ │ ├── Button.js ← exposed as remote/Button
│ │ └── UserCard.js ← exposed as remote/UserCard
│ └── pages/
│ ├── _document.js
│ ├── _app.js
│ └── index.js
│
└── package.json ← yarn workspaces root
| Tool | Version |
|---|---|
| Node.js | 20 LTS (via nvm) |
| Yarn | 1.x classic |
nvm install 20 --lts && nvm use 20# If you have Yarn Berry (2+) installed globally, pin this project to Yarn 1:
yarn set version classic
yarn installThe
resolutionsfield in rootpackage.jsonpins webpack to5.88.2. This is required — newer webpack 5 versions moved internal paths that@module-federation/enhanceddepends on (create-schema-validation), causing build errors.
flushChunksonly works correctly after a production build. In dev mode chunk filenames are not content-hashed and the stats file mapping is unreliable.
# Step 1 — build remote first (host's build depends on it)
yarn build:remote
# Step 2 — build host
yarn build:host
# Step 3 — start both (in two separate terminals)
yarn start:remote # → http://localhost:3001
yarn start:host # → http://localhost:3000After yarn build:remote, the remote emits two copies:
# client copy — served publicly, fetched by flushChunks at runtime
cat remote/.next/static/chunks/federated-stats.json | jq .
# server copy — used when host and remote share a filesystem
cat remote/.next/server/federated-stats.json | jq .The key section is federatedModules[].exposes:
{
"federatedModules": [{
"remote": "remote",
"entry": "static/chunks/remoteEntry.js",
"exposes": {
"./Button": ["static/chunks/__federation_expose_Button.{hash}.js"],
"./UserCard": ["static/chunks/__federation_expose_UserCard.{hash}.js"]
}
}]
}This is what ChunkCorrelationPlugin produces — it runs stats.toJson() on
the client webpack compilation and maps each expose key to the actual
content-hashed chunk filename webpack emitted for it.
[MF] ── flushChunks START ──────────────────────────────
[MF] usedChunks before flush: Set(2) { 'remote/Button', 'remote/UserCard' }
[MF] Resolved client chunks to inject: [
'http://localhost:3001/_next/static/chunks/__federation_expose_Button.{hash}.js',
'http://localhost:3001/_next/static/chunks/__federation_expose_UserCard.{hash}.js'
]
[MF] ── flushChunks END ────────────────────────────────
Cmd+U / Ctrl+U — look in <head> for:
<script src="http://localhost:3001/_next/static/chunks/__federation_expose_Button.{hash}.js" async></script>
<script src="http://localhost:3001/_next/static/chunks/__federation_expose_UserCard.{hash}.js" async></script>These are injected by <FlushedChunks> before React's own scripts.
Without them, React would try to hydrate the SSR'd HTML of the remote
components without having their JS — causing a hydration failure or
loading flash.
http://localhost:3000/debug — renders the raw federated-stats.json
inline with field annotations.
Also directly accessible at:
http://localhost:3001/_next/static/chunks/federated-stats.json
yarn build:remote
└─ webpack client compilation
└─ ChunkCorrelationPlugin.apply()
└─ compiler.hooks.done.tapAsync(...)
└─ stats.toJson({ chunks: true, chunkModules: true, reasons: true })
└─ walks module graph
└─ for each federatedModule:
maps exposeKey → emitted client chunk filename
└─ writes: remote/.next/static/chunks/federated-stats.json
└─ writes: remote/.next/server/federated-stats.json
Browser → GET localhost:3000
│
├─ [Next.js] _document.getInitialProps() runs
│ │
│ ├─ revalidate()
│ │ └─ dynamic require('@module-federation/node/utils')
│ │ └─ ⚠️ re-evaluates flush-chunks.js
│ │ └─ globalThis.usedChunks = new Set() ← RESETS the Set
│ │
│ ├─ Document.getInitialProps(ctx) ← page renders here
│ │ └─ dynamic(() => import('remote/Button'))
│ │ └─ NodeFederationPlugin intercepts import()
│ │ └─ fetches remote's SSR remoteEntry.js
│ │ └─ registers remote in globalThis.__FEDERATION__.__INSTANCES__
│ │
│ ├─ manually: globalThis.usedChunks.add('remote/Button')
│ │ globalThis.usedChunks.add('remote/UserCard')
│ │ (required in 8.x — see bug note below)
│ │
│ └─ flushChunks()
│ ├─ reads globalThis.usedChunks → ['remote/Button', 'remote/UserCard']
│ ├─ for each entry, splits on '/' → remote='remote', request='./Button'
│ ├─ getAllKnownRemotes()
│ │ └─ walks globalThis.__FEDERATION__.__INSTANCES__[].moduleCache
│ │ └─ finds: remote.entry = 'http://localhost:3001/_next/static/ssr/remoteEntry.js'
│ ├─ derives statsFile URL:
│ │ entry.replace('remoteEntry.js', 'federated-stats.json').replace('ssr', 'chunks')
│ │ → 'http://localhost:3001/_next/static/chunks/federated-stats.json'
│ ├─ fetch(statsFile) → parse JSON
│ ├─ stats.federatedModules[0].exposes['./Button']
│ │ → ['static/chunks/__federation_expose_Button.{hash}.js']
│ └─ returns: ['http://localhost:3001/_next/static/chunks/__federation_expose_Button.{hash}.js', ...]
│
└─ render()
└─ <FlushedChunks chunks={...} />
└─ <script src="http://localhost:3001/_next/.../__federation_expose_Button.{hash}.js" />
← injected in <head> before React scripts
Expected: When import('remote/Button') is called server-side, the MF
runtime's onLoad hook wraps the module in a Proxy, and calling any method
on it fires globalThis.usedChunks.add(id).
Actual: The Proxy's get handler only fires when a method on the
exported module is called, not when the module is imported. Next.js
dynamic() imports the module server-side during the page render, but
_document.getInitialProps runs after the render — and by then, no method
was called on the component in the Node.js context (React renders it, but
the Proxy intercept isn't wired into React's createElement path).
Workaround: Manually populate globalThis.usedChunks in
_document.getInitialProps after revalidate() settles.
revalidate() does Promise.resolve().then(() => require('@module-federation/node/utils')).
This dynamic require re-evaluates flush-chunks.js which has this at the top level:
if (!globalThis.usedChunks) {
globalThis.usedChunks = new Set(); // ← runs every time the module is evaluated
}In Node.js, require() caches modules — but the dynamic require inside a
Promise microtask can bypass the cache in certain conditions, causing
flush-chunks.js to re-evaluate and reset the Set.
Consequence: Any usedChunks entries written before revalidate() are lost.
This is also the root cause of issue #4407 in module-federation-examples —
revalidate() is supposed to bust the server chunk cache but instead it breaks
the chunk tracking mechanism.
Workaround: Always populate usedChunks AFTER revalidate() in _document.
The 7.x docs and many blog posts show __remote_scope__._config as the
source of remote entry URLs. In 8.x this was replaced with
globalThis.__FEDERATION__.__INSTANCES__[].moduleCache. The old
__remote_scope__ is undefined in 8.x builds.
| Package | Pinned to | Why |
|---|---|---|
@module-federation/nextjs-mf |
8.4.5 |
8.8.24+ introduced a broken re-export of installInitialConsumes from @module-federation/webpack-bundler-runtime |
webpack |
5.88.2 |
@module-federation/enhanced requires webpack/lib/util/create-schema-validation which was moved/removed in newer webpack 5 patch versions |
next |
13.5.6 |
Pages Router with _document support. App Router is not supported by nextjs-mf |