next-federation
API Reference

@next-federation/server

Server-side runtime for island remotes: the island handler, the identity verifier and HTML cleanup. It ships two CLIs: nf-serve (self-hosted server) and...

Server-side runtime for island remotes: the island handler, the identity verifier and HTML cleanup. It ships two CLIs: nf-serve (self-hosted server) and nf-describe (describes a Module Federation remote as a components build).

Install

npm install @next-federation/server

Usage

server.ts
import { createIslandHandler } from '@next-federation/server'

export const handler = createIslandHandler({
  name: 'shop',
  buildId: 'v1',
  mode: 'production',
  reactVersion: '19.2.0',
  hosts: ['https://app.example'],
  issuers: { 'https://app.example': 'https://app.example/.well-known/jwks.json' },
  islands: { Panel: {}, Account: { private: true } },
  bootstrapUrl: () => 'https://shop.example/b/v1/assets/bootstrap.js',
  render: async (island, props, { idPlaceholder, host }) => ({
    html, // SSR markup containing idPlaceholder
    rscPayload, // Flight payload containing idPlaceholder
    css: ['https://shop.example/b/v1/assets/panel.css'],
  }),
})

Entry points

EntryExports
@next-federation/servercreateIslandHandler, corsHeaders, stripIslandHtml, createIdentityVerifier, getIdentity, runWithIdentity, requireIdentity, REQUIRES_IDENTITY
@next-federation/server/nodeserveBuilds, planRetention, DEFAULT_RETENTION, toNodeListener, installedVersion, components build helpers

API

createIslandHandler(options)

Returns a (req: Request) => Promise<Response> serving GET|POST <prefix>/_nf/island/<name> and GET <prefix>/_nf/health. The island protocol v1 owns the wire contract and the status table.

OptionTypeDefaultDescription
namestringrequiredRemote name and token audience.
buildIdstringrequiredThe build id.
mode'development' | 'production'requiredThe React mode of the build.
reactVersionstringrequiredThe island build's React version.
hostsstring[]requiredAllowed origins. '*' throws NF-002; others 403 NF-022.
islandsRecord<string, { private?: boolean }>requiredExposed islands. private: true needs a verified token. Unknown: 404 NF-021.
render(island, props, ctx) => Promise<{ html, rscPayload, css }>requiredRenders one island (below).
bootstrapUrl() => string | Promise<string>requiredAbsolute URL of the island bootstrap module.
issuersRecord<string, string>noneIssuer to JWKS URL map. Without it, any token is 401 NF-016.
allowInsecureHttpbooleanfalseAccept plain-http issuers outside loopback and development.
maxAgenumber60max-age of public responses, in seconds.
maxBodyBytesnumber65536POST body limit (413).
devbooleannoneLog NF-018 per stripped tag.
actionsActionRuntimenoneServes Server Actions. The Vite plugin supplies it.
maxActionBodyBytesnumber1048576Server Action body limit (413).
actionsRequireIdentitybooleanfalseEvery action needs a verified token (401 NF-014).

render gets ctx with idPlaceholder (must appear in html and rscPayload) and host ({ basePath, locale }). css URLs must be absolute. A throw is a bare 500.

Every response carries Vary: Origin, Authorization. A success without a token is public, max-age=<maxAge>, one with a token is private, no-store, and every error is no-store.

corsHeaders(req, hosts)

The handler's CORS logic as a plain function.

stripIslandHtml(html)

Removes what React would hoist or run from island SSR HTML (<script>, <link>, <meta>, <base>, <title>, hoistable <style>). Returns { html, removed }. It is not a sanitizer.

const { html, removed } = stripIslandHtml(islandHtml)

createIdentityVerifier(options)

Returns (req: Request) => Promise<IdentityOutcome>. Throws NF-002 for an invalid issuer or JWKS URL.

OptionTypeDefaultDescription
audiencestringrequiredThis remote's name.
issuersRecord<string, string>requiredExact iss to JWKS URL. From configuration only.
maxAgeSecondsnumber900Reject tokens whose iat is older than this.
allowInsecureHttpbooleanfalseAccept plain-http issuers outside loopback and development.
const verify = createIdentityVerifier({
  audience: 'shop',
  issuers: { 'https://host.example.com': 'https://host.example.com/.well-known/jwks.json' },
})

const outcome = await verify(request)
// { kind: 'anonymous' } | { kind: 'verified', identity } | { kind: 'invalid', code } | { kind: 'unavailable' }
if (outcome.kind === 'verified') {
  await runWithIdentity(outcome.identity, () => render())
}
OutcomeWhenRespond
anonymousNo Authorization header.render
verifiedA valid token.render
invalidBad token (NF-014) or issuer not in the map (NF-016).401
unavailableJWKS unreachable, timed out (2 s) or bad (NF-015).503

Tokens are ES256 and need exp, iat and sub. Skew tolerance is 30 s; JWKS is cached up to 10 minutes. See Rotate a signing key for key rotation.

getIdentity() and runWithIdentity(identity, fn)

runWithIdentity exposes identity to fn. getIdentity() returns it, or null when outside one or anonymous.

requireIdentity(fn)

Wraps a Server Action so a call without a verified token is refused (401 NF-014). Also exported from @next-federation/island.

export const placeOrder = requireIdentity(async () => {
  // ...
})

serveBuilds(options)

From @next-federation/server/node. A self-hosted production server that keeps retained builds of a remote online. It returns { live, retired, current, port, close() }. Operator rules: Self-hosted skew.

import { serveBuilds } from '@next-federation/server/node'

const served = await serveBuilds({ dir: './builds', port: 4100 })
OptionTypeDefaultDescription
dirstringrequiredBuilds folder: <dir>/<buildId>/{client,rsc,ssr}.
portnumberrequiredPort to bind. 0 picks a free one.
hoststringnoneHost to bind. nf-serve defaults to 127.0.0.1.
currentstringthe newest buildThe current build id.
retention{ maxBuilds?, minAgeMs? }3 builds, 24 hoursWhich builds stay live.
maxBodyBytesnumberthe protocol limitRequest body cap while proxying.
maxActionBodyBytesnumber8 MiBBody cap for /_nf/action.
upstreamTimeoutMsnumber30000Wait for a build's response headers. Exceeded: 504.
compressionCacheBytesnumber64 MiBIn-memory cache cap for brotli and gzip files.
onExit({ buildId, code, signal }) => voidnoneOn build process death. That build answers 502.
  • Retired builds answer 410 {"error":"NF-023"}.
  • An affected react-server-dom-webpack build is refused (NF-041).
  • A kind: "components" build is static and serves /_nf/components.json.
  • Text files of at least 1 KB are sent brotli or gzip encoded.

planRetention(builds, now, retention, current?)

Returns { current, live, retired } for { buildId, builtAt } entries. Throws NF-002 for no builds. DEFAULT_RETENTION is { maxBuilds: 3, minAgeMs: 86400000 }.

toNodeListener(handler)

Adapts a Web handler to a Node listener.

nf-serve

The CLI for serveBuilds. Exits non-zero when a build dies, so use a supervisor.

nf-serve --dir ./builds --port 4100 [--host 127.0.0.1] [--current <buildId>] \
  [--max-builds 3] [--min-age-hours 24]

nf-describe

Writes nf-components.json and nf-build.json for a built Module Federation 2.0 remote. See Rspack or webpack remote.

nf-describe --dir dist/<buildId> [--ssr-entry server/remoteEntry.js | --no-ssr] \
  [--base <url>] [--build-id <id>] [--types] [--allow-insecure-http]
nf-describe --dir dist/<buildId> --verify [--public-key <JWK JSON | JWK file>]...
FlagDescription
--dirThe build folder. Its Module Federation output is in client/.
--ssr-entry, --no-ssrNeeded when client/mf-manifest.json names no ssrRemoteEntry (NF-002).
--typesIndex and sign client/@mf-types/. Fails without the folder (NF-002).
--verify, --public-keyCheck a described build (NF-027 otherwise).

The descriptor is signed when NF_COMPONENTS_SIGNING_KEY holds a private EC P-256 JWK. Describing without it drops an existing signature and still exits 0, and hosts render an unsigned build in the browser only (NF-028). Run the installed binary, not npx.

describeComponentsBuild, verifyComponentsBuild, runDescribeCli and the descriptor helpers (createDescriptorFile, collectServerIntegrity, collectBrowserAssets, collectTypesIndex, writeTypesIndex) are exported from @next-federation/server/node.

Learn more

License: MIT

On this page