Skip to content

feat(ssr): rewriteModulePreloads for native import maps (#171) - #213

Merged
Aukevanoost merged 5 commits into
native-federation:mainfrom
dathaynha:feat/ssr-rewrite-module-preloads
Nov 27, 2026
Merged

Aukevanoost merged 5 commits into
native-federation:mainfrom
dathaynha:feat/ssr-rewrite-module-preloads

Conversation

@dathaynha

@dathaynha dathaynha commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #171

Problem

With esmsInitOptions: { shimMode: false }, @angular/ssr adds a <link rel="modulepreload"> for each lazy chunk of the rendered route before </body>. The browser links those modules as soon as it reads them, before initFederation has added the import map, so a chunk that imports a shared package cannot resolve it and the app does not boot:

Failed to bootstrap application TypeError: Failed to resolve module specifier "@angular/core"

Fix

rewriteModulePreloads(res: Response | null), exported from a new ./ssr entry, in the shape agreed in the issue:

  • It acts only on HTML responses whose esms-options start with {"shimMode":false, allowing other attributes after type (the nonce that ngCspNonce adds). There it rewrites <link rel="modulepreload" to <link rel="preload" as="script" crossorigin and drops content-length.
  • Everything else is returned as the same Response: shim mode, non-HTML responses, pages without esms-options, pages with nothing to rewrite, and null.
  • All three inputs are fixed literals: @angular/ssr writes <link rel="modulepreload" href="…"> (appendPreloadHintsToHtml), @angular/build writes rel first, and the builder writes shimMode as the first key.
import { rewriteModulePreloads } from '@angular-architects/native-federation/ssr';

app.use((req, res, next) => {
  angularApp
    .handle(req)
    .then(rewriteModulePreloads)
    .then((response) => (response ? writeResponseToNodeResponse(response, res) : next()))
    .catch(next);
});

ng add is unchanged. I'll open the docs example on native-federation-website once this one is in.

Tests

src/ssr.spec.ts: 15 specs for the helper, including a streamed body (the server-rendered path), the content type @angular/ssr sends (text/html;charset=UTF-8), a nonce on the esms-options tag and on the links, and a pass-through whose body is still readable afterwards. One more spec runs @angular/build's augmentIndexHtml (loaded the way assets.spec.ts loads Angular's originals) and checks it still writes rel first for modulepreload hints, so a change upstream fails CI on the next bump.

The verify workflow's steps pass locally on Node 24 and pnpm 11, and dist/package.json exports ./ssr. (On macOS one existing spec, sourcemap-ignorelist-plugin.spec.ts, also fails on main, because os.tmpdir() is a symlink; with TMPDIR set to its real path all 500 pass.)

Measured again with the minimal version, on a host built with this adapter line (Angular 22.2, shimMode: false, a production build served by AngularNodeAppEngine), with one prerendered and one server-rendered lazy route:

Browser Without the helper With the helper
Chromium the bootstrap error above, on both routes boots
Safari 27.2 boots boots
WebKit (Playwright) boots boots

Each chunk was requested once in every case (Network events in Chromium and WebKit, Resource Timing in Safari). Firefox is left out, as you noted in the issue: it rejects an import map added after the first module script, so shimMode: false does not work there with or without this change.

In Chromium and WebKit, the same results hold with ngCspNonce on <app-root>, and with the helper the dev server (ng serve) boots too. With subresourceIntegrity: true, Chromium requests the hinted chunks twice, with or without the helper: Angular's SSR hints carry no integrity while the imports do, so this PR doesn't change it.

…ation#171)

With shimMode: false, @angular/ssr's route modulepreload hints link lazy
chunks before initFederation adds the import map, so a chunk importing a
shared package fails to resolve it. The helper, exported from ./ssr,
rewrites those hints to <link rel="preload" as="script" crossorigin> on
HTML responses whose esms-options set shimMode to false, and drops
content-length. Everything else passes through unchanged.
\btype matched data-type="esms-options", so a decoy block before the real
one decided the mode. Guard it like the rel match, and note that the first
block wins.
Comments and <script> bodies were searched like markup, rel or
crossorigin inside another attribute's value counted as the attribute,
a > inside a quoted value ended the tag early, and <link-card> counted
as <link>. Comments and script elements are now matched whole (to the
end of the page when unclosed, as browsers do) and skipped, quoted
values may contain >, and rel, type, as and crossorigin are read from
parsed attributes. Only the rel attribute changes; the tag name keeps
its case. A page in a charset other than UTF-8 is passed through rather
than re-encoded.

@Aukevanoost Aukevanoost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this fixes it. I reproduced #171 in Chromium against a production SSR build (Angular 22.2.6, shimMode: false, a lazy host route). It fails without the helper and boots with it, and each chunk is fetched once. The same holds for the minimal version suggested below.

Two smaller asks:

  • Add a spec that reads @angular/build's src/utils/index-file/augment-index-html.js (resolved the way src/builders/remote/assets.spec.ts does) and checks it still writes rel first for modulepreload hints, so a change upstream fails CI on the next bump.
  • In the docs PR: with crossOrigin: 'use-credentials', the rewritten preloads aren't reused, because the helper adds a bare crossorigin. A sentence is enough.

Comment thread src/ssr.ts Outdated
@@ -0,0 +1,95 @@
// Comments and `<script>` bodies are matched whole (to the end, if unclosed, as browsers do) so

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's take you up on the minimal version. Both inputs are fixed: @angular/ssr writes <link rel="modulepreload" href="…"> (appendPreloadHintsToHtml), @angular/build puts rel first, and our builder writes shimMode as the first key. The comment/script skipping, attribute parsing, case folding, first-block rule and charset check cover markup none of them produce.

One thing a plain literal would miss: with ngCspNonce, Angular adds a nonce to the options tag (<script type="esms-options" nonce="…">), so the detection must allow attributes there:

const MODULE_PRELOAD = '<link rel="modulepreload"';
const NATIVE_IMPORT_MAPS = /<script type="esms-options"[^>]*>\{"shimMode":false/;

// `crossorigin` keeps the preload in CORS mode, so the module import reuses the response (#171).
export async function rewriteModulePreloads(res: Response | null): Promise<Response | null> {
  if (!res?.body || !res.headers.get('content-type')?.includes('text/html')) return res;

  const html = await res.clone().text();
  if (!NATIVE_IMPORT_MAPS.test(html) || !html.includes(MODULE_PRELOAD)) return res;

  const headers = new Headers(res.headers);
  headers.delete('content-length');
  return new Response(html.replaceAll(MODULE_PRELOAD, '<link rel="preload" as="script" crossorigin'), {
    status: res.status,
    statusText: res.statusText,
    headers,
  });
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 935b8f5, as you wrote it, wrapped to 100 columns. I also checked it on a real build with ngCspNonce: the options tag comes out as <script type="esms-options" nonce="…">{"shimMode":false}, and every preload is rewritten.

Comment thread src/ssr.ts Outdated
index: number;
}

/** Wraps `AngularNodeAppEngine.handle()` in `server.ts` under `shimMode: false` (#171). */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this a single // line (house style, see .claude/rules/comments.md).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, it is the // line from your version.

Comment thread src/ssr.spec.ts Outdated
return new Response(body, {
status: 200,
headers: {
'content-type': 'text/html; charset=utf-8',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Angular sends text/html;charset=UTF-8 (no space, upper case). Please use that as the default here: currently removing the .toLowerCase() in ssr.ts keeps every spec green while the helper would do nothing in production.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the fixture now sends text/html;charset=UTF-8, as @angular/ssr does.

Comment thread src/ssr.spec.ts Outdated
expect(out!.statusText).toBe('Not Found');
});

it('does not add a second crossorigin', async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the minimal version, these specs go: second crossorigin, comment, attribute text, script body, existing as, case, first block, unclosed script and charset (none of those inputs come from Angular or our builder). Please add one with a nonce on the esms-options tag and on the links, as ngCspNonce produces.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed those nine and added keeps the nonce that ngCspNonce adds to esms-options and to the links. I also renamed leaves unparsable esms-options alone to needs the builder's exact {"shimMode":false prefix, since nothing is parsed any more.

@Aukevanoost

Copy link
Copy Markdown
Contributor

Couple of small things, for the rest it looks great!

@angular/ssr writes `<link rel="modulepreload" href="…">`, @angular/build
puts `rel` first and the builder writes `shimMode` as the first key, so
a literal match replaces the attribute parsing.

A spec runs @angular/build's augmentIndexHtml so a change to that order
fails CI. The fixtures send `text/html;charset=UTF-8`, as Angular does,
and one carries the nonce that ngCspNonce adds.
@dathaynha

Copy link
Copy Markdown
Contributor Author

Thanks for reproducing it. Both asks are in 935b8f5:

  • src/ssr.spec.ts runs augmentIndexHtml from @angular/build (loaded as in assets.spec.ts) and checks that modulepreload hints still start with rel.
  • The use-credentials sentence is in the docs draft for native-federation-website, which I will open once this is merged.

I updated the description for the minimal version and measured the browsers again with it.

@Aukevanoost Aukevanoost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Aukevanoost
Aukevanoost merged commit 30a775e into native-federation:main Nov 27, 2026
1 check passed
Aukevanoost added a commit that referenced this pull request Nov 27, 2026
Backports 22.2.5..22.3.0 onto the Angular 21 layout.

Incoming:
- #214: @softarc/native-federation ~4.11.0; fromPackageJson() takes an
  optional base config and autoShareScope resolves projectPath against
  workspaceRoot.
- #171/#213: rewriteModulePreloads (./ssr export) for native import maps.
- #209: ngServerMode is set in exposed-module bundles.
- #210: the prod node preload no longer passes hostInstances.
- #215: NodePackageInstallTask comes from @angular-devkit/schematics/tasks.
- Tag-triggered release workflow (staged npm publish).

Angular 21 specific adaptations:
- Left out the Angular 22.3 bump: kept the -v4 name, 21.2.18 version and
  ng21 pins; bumped @softarc/native-federation to 4.11 by hand.
- Kept the `// upstream:` tags at v21.2.19 (1a728258d6) and the 21.2
  debugOptimize note.
- Dropped the remote builder, share-utils.spec.ts and
  tools/esbuild/sourcemap-ignorelist-plugin.ts as before.
- @angular/ssr 21.2 emits the same modulepreload markup as 22, so
  rewriteModulePreloads applies unchanged.
- follow-redirects@1 override raised to ^1.16.2 for a high advisory.
- pnpm-lock.yaml regenerated rather than merged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSR + shimMode: false: route modulepreload hints race the runtime import map, lazy routes fail to load

2 participants