Page loaded: Taking Apart an Angular SSR Page

Photo by Megan Clark on Unsplash

Performance & SSR

Taking Apart an Angular SSR Page

A server-rendered Angular page makes four trips: rendered on the server, written down, adopted by the browser and caught up on the clicks it missed. Each one has a rule, and most hydration errors are one of them broken.

Miguel Carino
Focus
Front-end web architecture, Angular, team leadership, and stakeholder communication
Experience
25+ years turning enterprise web complexity into maintainable products

NG0500: During hydration Angular expected <div> but found <p>.

That's the first line of the error Angular throws, in a development build, when the page it's trying to take over doesn't match the page it expected. For a lot of developers it's the first sign that hydration has rules at all.

Some context for anyone who hasn't met the word. Server-side rendering (SSR) means the server sends finished HTML, so the page has content before any JavaScript runs. Hydration is what happens next. The browser has already turned that HTML into the DOM, its live tree of elements, and Angular starts up and adopts those elements in place instead of building the page again. The error above means the adoption failed. Angular went to claim a <div> and found a <p> someone else had put there.

I wanted to see every rule that message guards, in a page I could take apart. So I followed one page of demo.miguelcarino.com, the Angular app I keep for this blog's examples, from the build to the first click. The page is /seo. I've written before about one mismatch that only some users saw, and this time I wanted the whole page.

The render happens at build time

The demo prerenders, which is SSR done once at build time instead of on every request. The build renders each route on the server and writes the result to its own index.html, and the host serves those files as they are. Which routes get that treatment is set in app.routes.server.ts, shown here with its comments trimmed:

import { RenderMode, ServerRoute } from '@angular/ssr';

export const serverRoutes: ServerRoute[] = [
  {
    path: 'fundamentals/admin',
    renderMode: RenderMode.Client,
  },
  {
    path: '**',
    renderMode: RenderMode.Prerender,
  },
];

The wildcard prerenders every route Angular can find in the route table, so a new page is covered without anyone adding it to a list. The one exception sits behind a route guard that checks a role stored in the visitor's browser. At build time there is no visitor, the guard says no and there's no page to write. That route renders in the browser instead.

You can see the result on the page itself. The SSR section of the demo prints where it was rendered, and the HTML file says "This view rendered on the server." Load it in a browser and the same sentence reads "the browser (after hydration)." Different text in the same element is fine, because hydration checks the elements and their order, then adopts the text node and updates it like any other binding.

What the server writes down

A plain HTML page can't tell Angular which node belongs to which component. So the server leaves notes. Here is the start of the prerendered <body> for /seo, trimmed to the parts that matter and with the first script's body cut:

<body><!--nghm--><script type="text/javascript" id="ng-event-dispatch-contract">…</script><script>window.__jsaction_bootstrap(document.body,"ng",["click","change"],[]);</script>
<foo-root ngh="8" ng-server-context="ssg">

Further down, the button from the event replay example, trimmed the same way:

<button foo-button="" variant="secondary" type="button" ngh="6" jsaction="click:;"><!----><span class="foo-button__label">Count a click</span></button>

And near the end of the file, the transfer state script, cut off after its first few entries:

<script id="ng-state" type="application/json">{"__nghData__":[{},{"n":{"17":"15f"},"t":{"17":"t0","20":"t1","26":"t3"},

Each ngh attribute is an index into the __nghData__ array in that script. The entry at that index describes the component's view as the server rendered it, such as how many nodes each @if or @for produced and which of them aren't where a simple walk would expect. The empty <!----> comments are anchors that mark where those blocks sit. The <!--nghm--> comment right after <body> is an integrity marker. If something between the server and the browser strips comments out, the HTML minifier on a content delivery network (CDN), for example, Angular notices the marker is gone and reports NG0507 instead of guessing.

This is a shipping manifest. The browser gets the boxes and a list of what's in each one.

The browser adopts the DOM

The browser half is one line in app.config.ts, shown here with the providers around it trimmed:

export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideClientHydration(withEventReplay(), withIncrementalHydration()),
    provideBrowserGlobalErrorListeners(),
  ],
};

When the app starts, Angular creates the root component on the <foo-root> that's already there. It reads that element's ngh value, looks up the entry and walks the existing nodes, claiming each one for the template node that should own it. It attaches listeners and bindings to nodes it didn't create. When a node isn't what the template says should be there, that's NG0500. Usually it's a component that inserted an element with document.createElement, or a browser extension that did the same. Invalid HTML can cause it too, since the browser's parser rewrites it before Angular ever looks.

The same line also turns on the HTTP transfer cache. A request the server already made during the render is stored in the page and isn't sent again on load.

Clicks that arrive before the code

There's a gap between the HTML showing up and the app's JavaScript finishing its download. On a slow phone it can last seconds, and a visitor sees a button and presses it.

That's what the jsaction="click:;" on the button is for. The server marks every element with a listener. The inline ng-event-dispatch-contract script, started by the one-line script after it, listens at the root of the page for the event types the app uses, here click and change, and records any that land on a marked element. After hydration Angular replays them to the real handlers. The library behind it, JSAction, is the one Wiz, the framework Google uses for its own apps, relies on across hundreds of them, google.com included.

The event replay example is a single button that counts clicks. The demo's end-to-end test proves it with Playwright, the browser automation tool. It holds the app's entry script on the network, clicks, checks that nothing counted, then lets the script through. From ssr-hydration.spec.ts, trimmed to that one test:

import { expect, test } from '@playwright/test';

test('a click made before hydration is replayed once the app loads', async ({ page }) => {
  // Hold the app's entry script until the click has happened.
  let release: () => void = () => undefined;
  const held = new Promise<void>((done) => (release = done));
  await page.route(/\/main(-[\w-]+)?\.js(\?.*)?$/, async (route) => {
    await held;
    await route.continue();
  });

  await page.goto('/seo', { waitUntil: 'commit' });
  const button = page.getByRole('button', { name: 'Count a click' });
  const count = page.locator('.replay-demo__count');
  await expect(button).toBeVisible();

  await button.click();
  // No JavaScript has run, so nothing has counted it yet.
  await expect(count).toHaveText('Clicks counted: 0');

  release();
  await expect(count).toHaveText('Clicks counted: 1');
});

The click made with no JavaScript running is counted once the JavaScript arrives.

The part hydration doesn't adopt

Hydration starts at the app's root element, in the <body>. It never claims anything in the <head>. Services like Title and Meta still change the head, but they find their tags with a query each time instead of owning them. The demo had a bug from exactly that. After hydration, the demo's head held two copies of its JSON-LD structured data, the machine-readable description of the page that search engines read, because the code that writes it appended a new script in the browser instead of reusing the server's. The fix finds the script by id first. That bug gets its own post. The rule it taught is short: anything you add to the head during the render is already there when the browser starts, so look for it before you create it.

Reading the config line closely

In current Angular, withEventReplay() and withIncrementalHydration() are both redundant. provideClientHydration() turns on incremental hydration by default, which lets a @defer block stay dehydrated until a trigger like hydrate on viewport fires, and incremental hydration turns on event replay because a dehydrated block needs it. withIncrementalHydration() is now deprecated. The demo keeps both calls so the line says what the app relies on. A shorter line would behave the same.

When another mode fits better

Prerendering fits this site because every page is the same for every visitor and the host serves static files. Other apps need other modes, and Angular lets you set them per route.

Rendering on each request, RenderMode.Server, fits pages built from data that changes by the minute or by user, like a product page with live stock. It needs a Node server running in production, which the demo's shared hosting doesn't offer, and nothing on these pages changes between deploys.

Client-only rendering, RenderMode.Client, is the simplest of the three. For an app behind a login, where search engines never look and the first screen is a spinner anyway, it can be the right call. The demo uses it for exactly one route.

There's also ngSkipHydration, an attribute that tells Angular to throw away one component's server DOM and render it fresh. Angular's docs call it a last resort. I'd use it for a third-party widget I can't change. For my own code, a mismatch means the browser's first render did something the server's didn't, and the fix belongs in that component.

Find the Step That Broke

Every hydration error I've read was one of those trips finding something it didn't expect: a node the browser's first render made differently, notes stripped out between the server and the browser or a component that touched the DOM before Angular claimed it. So when one shows up, I start by asking which trip it happened on, because each one points at a different file.