Blog

Part 29 · Server-Side Rendering and Incremental Hydration in Angular

With server-side rendering, the server sends a finished page and the browser takes it over. This part covers ng new –ssr, render modes, hydration, incremental hydration with @defer, the HTTP transfer cache and code that breaks on the server.

So far, the browser gets an almost empty page, downloads the JavaScript, runs it, and only then is there anything to read. On a slow phone that’s a blank screen for a while, and a search engine may see nothing at all.

This part covers server-side rendering (SSR): ng new --ssr, the files it adds, render modes, hydration, incremental hydration with @defer, the HTTP transfer cache, and code that breaks on the server. It builds on afterNextRender from Part 10, httpResource from Part 19 and @defer from Part 27. SSR needs a server, so this part uses a new project instead of the practice project from Part 1. Every code block here is a file, or part of a file, from that project. Each one was built with Angular 22.3, run on the server and checked in a browser before this was published.

Try this first

Make a new project with SSR switched on, and start it:

npx @angular/cli@22 new ssr-demo --ssr --inline-template --inline-style --style=css --ai-config=none
cd ssr-demo
ng serve

The flags are the ones from Part 1; --ssr answers the SSR question for you. Open http://localhost:4200, then open the page’s source (Ctrl+U, or right-click and View Page Source). Do the same in your practice project from Part 1.

Before you look, guess. Both pages show a heading once they’ve loaded. Which of the two has the heading in its source?

Only the new one. The practice project’s source has the <app-root></app-root> from its index.html, empty. The browser fills it in later, with JavaScript. In the SSR project, the heading is already there. Here’s the <app-root> element from the page ng build wrote for it:

<app-root ng-version="22.3.2" ngh="0" ng-server-context="ssg"><h1>Hello, ssr-demo</h1><router-outlet></router-outlet><!----></app-root>

With ng serve, that somebody is the dev server. In production, it’s either ng build itself, which renders pages ahead of time as it did here, or a Node.js server that ng build makes. The extra attributes are notes for the browser; we’ll read them below.

What server-side rendering is, and why

Without SSR, Angular renders in the browser. That’s called client-side rendering. The server sends index.html and the JavaScript, and nothing more.

With SSR, the server runs your Angular app for each request, renders the page to HTML, and sends that. The browser shows the HTML at once. Then it downloads the same JavaScript as before, and Angular takes over the page that’s already there. That taking over is hydration.

Three things get better:

  • First paint. The reader sees content before any JavaScript has run.
  • Search engines. A crawler that reads the HTML gets the words and the links.
  • Link previews. A chat app reads your <title> and meta tags from the HTML, often without running JavaScript.

The price: pages rendered per request need a server that runs Node.js, not just a folder of files. And your components now run in two places, on the server and in the browser. Code that assumes a browser breaks on the server.

The files –ssr adds

ng new --ssr makes the usual project plus four files. For a project you already have, ng add @angular/ssr adds the same four and updates angular.json, package.json, tsconfig.app.json and app.config.ts.

  • src/server.ts is a small Express web server. It serves the built files and hands other requests to Angular.
  • src/main.server.ts starts the app on the server, as main.ts does in the browser.
  • src/app/app.config.server.ts holds the providers for the server.
  • src/app/app.routes.server.ts says how each route is rendered.

Here’s src/app/app.config.server.ts (all files in this part are shown after running prettier on them):

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';

const serverConfig: ApplicationConfig = {
  providers: [provideServerRendering(withRoutes(serverRoutes))],
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

mergeApplicationConfig adds the server’s providers to the browser’s config, so app.config.ts runs on the server too. provideServerRendering(withRoutes(serverRoutes)) switches on rendering, with the routes from app.routes.server.ts. ng new writes this one:

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

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

'**' matches every path. RenderMode.Prerender means “render this page once, when the app is built”. That’s why the Try this first page said ng-server-context="ssg": SSG is short for static site generation, which is another name for prerendering.

The browser side changes too. ng new --ssr adds provideClientHydration() to src/app/app.config.ts:

import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideClientHydration(),
  ],
};

A small app to render

Our app has three pages: a list of books from an API, an About page, and an Account page. The API lives in src/server.ts, which already is a web server. Add these lines after const angularApp = new AngularNodeAppEngine();:

const books = [
  { id: 1, title: 'Dune' },
  { id: 2, title: 'Emma' },
];

app.get('/api/books', (req, res) => {
  console.log('API: GET /api/books');
  res.json(books);
});

app.get answers /api/books with the list as JSON. The console.log goes to the server’s terminal, so we can count API calls.

The Books page loads them with httpResource from Part 19. It also has two child components, which we’ll meet in a moment. src/app/books.ts:

import { httpResource } from '@angular/common/http';
import { Component, inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { LastVisit } from './last-visit';
import { LikeButton } from './like-button';

interface Book {
  id: number;
  title: string;
}

@Component({
  selector: 'app-books',
  imports: [LastVisit, LikeButton],
  template: `
    <h1>Books</h1>
    <ul>
      @for (book of books.value(); track book.id) {
        <li>{{ book.title }}</li>
      }
    </ul>
    <app-last-visit />
    @defer (hydrate on interaction) {
      <app-like-button />
    }
  `,
})
export class Books {
  protected readonly books = httpResource<Book[]>(() => '/api/books', { defaultValue: [] });

  constructor() {
    const where = isPlatformBrowser(inject(PLATFORM_ID)) ? 'browser' : 'server';
    console.log(`Books created on the ${where}`);
  }
}

PLATFORM_ID is a token that says where the app is running. isPlatformBrowser turns it into true in the browser and false on the server. We use it here only to log where the constructor ran.

src/app/like-button.ts is a button that counts clicks. Its afterNextRender logs when it runs:

import { afterNextRender, Component, signal } from '@angular/core';

@Component({
  selector: 'app-like-button',
  template: `<button (click)="like()">Likes: {{ likes() }}</button>`,
})
export class LikeButton {
  protected readonly likes = signal(0);

  constructor() {
    afterNextRender(() => console.log('LikeButton is running in the browser'));
  }

  protected like() {
    this.likes.update((n) => n + 1);
  }
}

src/app/last-visit.ts remembers your last visit in localStorage, the browser’s small key-value store:

import { afterNextRender, Component, signal } from '@angular/core';

@Component({
  selector: 'app-last-visit',
  template: `<p>Last visit: {{ lastVisit() }}</p>`,
})
export class LastVisit {
  protected readonly lastVisit = signal('unknown');

  constructor() {
    afterNextRender(() => {
      this.lastVisit.set(localStorage.getItem('lastVisit') ?? 'first time here');
      localStorage.setItem('lastVisit', new Date().toDateString());
    });
  }
}

Why afterNextRender? The worked example below shows what happens without it.

src/app/app.ts is a menu and a <router-outlet>:

import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink, RouterOutlet],
  template: `
    <nav>
      <a routerLink="/">Books</a> | <a routerLink="/about">About</a> |
      <a routerLink="/account">Account</a>
    </nav>
    <router-outlet />
  `,
})
export class App {}

src/app/app.routes.ts lists the three pages, as in Part 16:

import { Routes } from '@angular/router';
import { About } from './about';
import { Account } from './account';
import { Books } from './books';

export const routes: Routes = [
  { path: '', component: Books },
  { path: 'about', component: About },
  { path: 'account', component: Account },
];

We’ll write about.ts and account.ts in the next section.

Render modes: server, build time or browser

app.routes.server.ts gives each path one of three render modes, from the RenderMode enum (a named set of constants):

  • RenderMode.Server: render on the server, for every request. For pages whose content changes, like our book list.
  • RenderMode.Prerender: render once, during ng build, and save the HTML as a file. For pages that are the same for everyone until you deploy again.
  • RenderMode.Client: don’t render on the server. The server sends the empty page, and the browser does everything, as without SSR.

Our src/app/app.routes.server.ts:

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

export const serverRoutes: ServerRoute[] = [
  { path: 'about', renderMode: RenderMode.Prerender },
  { path: 'account', renderMode: RenderMode.Client },
  { path: '**', renderMode: RenderMode.Server },
];

The most specific path wins, so 'about' beats '**' wherever you put it. (We checked with '**' first: /about was still prerendered.) We put '**' last so the list reads from specific to general. Here’s src/app/about.ts. It’s prerendered, and it adds a <link rel="canonical"> to the page’s <head>. That tag tells search engines the page’s main address.

import { Component, DOCUMENT, inject } from '@angular/core';

@Component({
  selector: 'app-about',
  template: `
    <h1>About</h1>
    <table>
      <tbody>
        <tr>
          <td>Books</td>
          <td>rendered on the server for every request</td>
        </tr>
        <tr>
          <td>About</td>
          <td>rendered once, when the app is built</td>
        </tr>
        <tr>
          <td>Account</td>
          <td>rendered in the browser only</td>
        </tr>
      </tbody>
    </table>
  `,
})
export class About {
  constructor() {
    const document = inject(DOCUMENT);
    if (document.head.querySelector('link[rel="canonical"]')) {
      return;
    }
    const link = document.createElement('link');
    link.rel = 'canonical';
    link.href = 'https://example.com/about';
    document.head.appendChild(link);
  }
}

There’s no global document on the server. inject(DOCUMENT) gives you the page’s document wherever the app runs: the real one in the browser, and the server’s own model of the page on the server. Changes you make to it on the server end up in the HTML that’s sent. The constructor runs again in the browser, during hydration and on every visit to the page, so it checks for an existing link first. Without it, each visit would add another link.

src/app/account.ts reads localStorage directly. That’s safe only because this page never runs on the server:

import { Component } from '@angular/core';

@Component({
  selector: 'app-account',
  template: `
    <h1>Account</h1>
    <p>Last visit: {{ lastVisit }}</p>
  `,
})
export class Account {
  protected readonly lastVisit = localStorage.getItem('lastVisit') ?? 'never';
}

Next, we’ll build the app and see what the server sends for each mode.

Running the real server

ng serve renders on the server, which is enough for most work. To run what you’d deploy, build it and start the Node.js server that the build wrote:

ng build
npm run serve:ssr:ssr-demo

The script name ends in your project’s name. The server listens on port 4000. The first time we opened http://localhost:4000, the page said only this:

Header "host" with value "localhost:4000" is not allowed.

and the server’s terminal said:

ERROR: Bad Request ("http://localhost:4000/").
Header "host" with value "localhost:4000" is not allowed.

That’s a safety check. Every request carries a Host header naming the server, and an attacker can fake it. So the production server only answers names you list. ng new writes an empty list, and an empty list allows nothing, not even localhost. The list lives in angular.json, under the build’s options:

            "security": {
              "allowedHosts": [
                "localhost"
              ]
            },

(We’ve left out the line after it, which links to Angular’s security guide.) Then build again: the list is baked into the build. Add your real domain name there before you deploy. You can also add names when the server starts, without a rebuild, with the NG_ALLOWED_HOSTS environment variable (a comma-separated list): NG_ALLOWED_HOSTS=localhost npm run serve:ssr:ssr-demo.

To see Angular’s full error messages and the hydration summary below, build with ng build --configuration development before npm run serve:ssr:ssr-demo. A production build shortens names in stack traces and reports only an error code. The error messages and console output in the rest of this part come from development builds. The server HTML we quote comes from a production build.

ng build now prints Prerendered 1 static route., and the folder dist/ssr-demo/browser/about/ has an index.html with the About page already in it, canonical link included. /about is served from that file and marked ng-server-context="ssg". / is rendered per request, and marked ng-server-context="ssr". And /account arrives like this:

<body ngcm="">    <app-root></app-root>

An empty <app-root>. There’s no ngh data, so there’s nothing to hydrate, and the browser renders the page from scratch. The ngcm attribute only tells Angular that this is on purpose, so it doesn’t warn about missing hydration data (we read that in Angular’s source).

Hydration: taking over the server’s page

Angular doesn’t throw the server’s HTML away and draw the page again. It hydrates: it runs your components again, walks the DOM the server made, and adopts each element instead of making a new one. Then it adds the event listeners. After that, the page is a normal Angular app.

For that, the server leaves notes. Here’s the <app-root> the server sent for /:

<app-root ng-version="22.3.2" ngh="2" ng-server-context="ssr"><nav><a routerlink="/" href="/" jsaction="click:;">Books</a> | <a routerlink="/about" href="/about" jsaction="click:;">About</a> | <a routerlink="/account" href="/account" jsaction="click:;">Account</a></nav><router-outlet></router-outlet><app-books ngh="1"><h1>Books</h1><ul><li>Dune</li><li>Emma</li><!----></ul><app-last-visit ngh="0"><p>Last visit: unknown</p></app-last-visit><!----><app-like-button jsaction="click:;keydown:;" ngb="d0" ngh="0"><button jsaction="click:;" ngb="d0">Likes: 0</button></app-like-button><!--ngh=d0--></app-books><!----></app-root>

The books are there: the server called the API and waited for the answer before it sent the page. Last visit: unknown is there because afterNextRender doesn’t run on the server. The notes:

  • Each ngh attribute points into a table of hydration data that the server put at the end of the page. It describes what’s inside each component, such as how many items an @for made.
  • jsaction marks elements with event listeners, so a click there can be recorded before Angular is ready. More on that below.
  • ngb="d0" marks elements inside the @defer block named d0.

The table is in a <script> at the end:

<script id="ng-state" type="application/json">{"6297af8e584ff750aab1c19d4ce46985a8cb6ba11d003af9c1a69d6f269b32b2":{"b":[{"id":1,"title":"Dune"},{"id":2,"title":"Emma"}],"h":{},"s":200,"st":"OK","u":"\u002Fapi\u002Fbooks","rt":"json"},"__nghData__":[{},{"t":{"4":"t0","6":"t1","7":"t2"},"c":{"4":[{"i":"t0","r":1,"x":2}],"6":[],"7":[{"i":"t1","r":1,"di":"d0","s":2}]}},{"c":{"9":[{"i":"c4288457431","r":1}]}}],"__nghDeferData__":{"d0":{"r":1,"s":2}}}</script>

That’s the transfer state: data the server hands to the browser. __nghData__ is the hydration table, and __nghDeferData__ describes the defer block. The long first key is something else: the /api/books response, with its body ("b"), status and URL. We’ll get to that.

provideClientHydration() is what reads these notes in the browser. In Angular 22.3 it switches on, by default:

  • hydration itself;
  • the HTTP transfer cache (below);
  • incremental hydration (below), which also switches on event replay: clicks and key presses that happen before a part of the page is hydrated are recorded and played back once it is.

In development builds, Angular logs a summary to the browser console. For /, it says:

Angular hydrated 3 component(s) and 30 node(s), 0 component(s) were skipped. 1 defer block(s) were configured to use incremental hydration. Learn more at https://v22.angular.dev/guide/hydration.

Three components: App, Books and LastVisit. The console also has Books created on the browser, and the server’s terminal has Books created on the server. Each of those components runs twice: once on the server to make the HTML, once in the browser to hydrate it. LikeButton isn’t in the count. It’s inside the @defer block.

Incremental hydration with @defer

Hydrating means downloading and running the code for every component on the page. Incremental hydration lets parts of the page stay as plain server HTML until they’re needed.

You mark those parts with @defer and a hydrate trigger. Part 27 covers @defer in the browser, where the block’s code loads when its trigger fires. With hydrate triggers, the server renders the block’s content, not a placeholder. The browser shows it at once, but doesn’t download its code until the trigger fires. That only applies when the page came from the server. If the reader reaches the block by navigating inside the app, Angular’s docs say the block falls back to its normal @defer trigger. Our Books page has:

    @defer (hydrate on interaction) {
      <app-like-button />
    }

LikeButton is in its own chunk, a separate JavaScript file. With the built server (or ng serve --no-hmr, see below), open / and look at the Network tab: the chunk isn’t loaded, and LikeButton is running in the browser isn’t in the console. The button shows Likes: 0, but nothing is listening to it.

Click it. Three things happen: the browser loads the chunk, Angular hydrates LikeButton (the console now has LikeButton is running in the browser), and the button says Likes: 1. The click that woke the block up wasn’t lost. Event replay recorded it through the jsaction attribute and played it back. The next click gives Likes: 2, like any button.

page in the browser loaded in the browser App Books Dune, Emma LastVisit Last visit: unknown Last visit: first time here LikeButton Likes: 0 Likes: 1 main.js like-button chunk hydrated: 3 components not hydrated: LikeButton hydrated: LikeButton your click click recorded (event replay) recorded click replayed Server HTML: readable; only a small script that records clicks App, Books, LastVisit hydrated; LikeButton is still plain HTML the click is recorded, not lost LikeButton hydrated, the click replayed: Likes: 1 The server sends finished HTML; the browser shows it at once main.js loads and hydrates everything outside the @defer block You click Likes: 0. Its code isn't loaded yet The chunk loads, LikeButton hydrates and handles the click

The page is readable before any code runs. Each part wakes up when it’s needed, and the click that woke it still counts.

Here are those steps in words, in case the animation doesn’t play for you:

  1. The server sends the finished HTML. The browser shows the books, Last visit: unknown and Likes: 0 straight away. No Angular code has run in the browser yet, only a small inline script that records clicks.
  2. main.js loads. Angular hydrates App, Books and LastVisit. LastVisit‘s afterNextRender runs and the text changes to first time here. LikeButton is inside @defer (hydrate on interaction), so it stays as plain HTML.
  3. You click Likes: 0. There’s no listener for it yet. Event replay records the click.
  4. The click is the trigger. The browser loads the like-button chunk, Angular hydrates LikeButton, and replays the recorded click. The button shows Likes: 1.

The other hydrate triggers follow the @defer triggers from Part 27: hydrate on idle, hydrate on viewport, hydrate on hover, hydrate on immediate, hydrate on timer(2s) and hydrate when followed by a condition. There’s also hydrate never: the block stays as server HTML for good. Exercise 3 tries it.

One trap with ng serve, which Part 27 met too. Its hot module replacement (HMR) swaps changed code into the open page while you edit. With HMR on, which is the default, the dev server prints this, and the browser console shows it too:

NG0751: Angular has detected that this application contains `@defer` blocks and the hot module replacement (HMR) mode is enabled. All `@defer` block dependencies will be loaded eagerly. Find more at https://v22.angular.dev/errors/NG0751

“Loaded eagerly” means the block’s code arrives with the rest of the page. The block still hydrates on its trigger: in our run, LikeButton hadn’t run before the click, and the click still gave Likes: 1. But you won’t see its chunk download in the Network tab.

The HTTP transfer cache

The Books page fetches /api/books. It runs on the server, so the server fetches the list. Then it runs again in the browser to hydrate. Does the browser fetch the list a second time?

No. Load / and watch the Network tab: there’s no request to /api/books. The server’s terminal shows one API: GET /api/books per page load. That’s the HTTP transfer cache. On the server, HttpClient saves each response in the transfer state, the long key in the ng-state script we saw. In the browser, the same request is answered from there, without going to the network. httpResource uses HttpClient, so it’s covered.

By default it caches GET and HEAD requests (and the newer QUERY method). It skips requests that carry login details (an Authorization or Cookie header, or withCredentials), requests and responses whose Cache-Control says no-store, no-cache or private, and responses that set a cookie. And the browser only uses the cache during its first render. When we navigated from About back to Books inside the app, the browser fetched /api/books itself. (The rules come from reading @angular/common/http‘s source; the navigation we ran.) withHttpTransferCacheOptions({...}) changes what’s cached. To see the difference, switch the cache off with withNoHttpTransferCache() in src/app/app.config.ts:

import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration, withNoHttpTransferCache } from '@angular/platform-browser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideClientHydration(withNoHttpTransferCache()),
  ],
};

Now one load of / makes two calls, and the Network tab shows the browser’s one. Put the cache back.

Worked example: localStorage on the server

Here’s a first try at LastVisit, without afterNextRender. It reads localStorage while the component is created:

import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-last-visit',
  template: `<p>Last visit: {{ lastVisit() }}</p>`,
})
export class LastVisit {
  protected readonly lastVisit = signal(localStorage.getItem('lastVisit') ?? 'first time here');
}

It builds without a complaint. TypeScript knows localStorage, because a project’s default settings include the browser’s types. Open / on a development build of the server, and the browser gets a 404 page with one line:

Cannot GET /

The real error is in the server’s terminal:

Books created on the server
ERROR ReferenceError: localStorage is not defined
    at <instance_members_initializer> (dist/ssr-demo/server/main.server.mjs:18452:5)
    at new _LastVisit (dist/ssr-demo/server/main.server.mjs:18450:17)

(We shortened the paths; yours start with your project’s folder.) Read it:

  • ReferenceError: localStorage is not defined: JavaScript found no variable called localStorage. Node.js isn’t a browser. It has no window and no global document. We ran Node.js 24, which has no localStorage either. (Node.js 25 is reported to have a partial one, giving localStorage.getItem is not a function instead; we didn’t run that.)
  • at new _LastVisit: it happened while creating LastVisit (the build adds the _). <instance_members_initializer> means a field’s starting value, here the signal(...) line.

Why a 404, and not an error page? The error stopped the router from showing the page, so Angular handed the request back to server.ts (that’s from reading @angular/ssr‘s source). Express had nothing else for /, and answered with its own “Cannot GET” page. Elsewhere it’s different: in the root App we got a 500, and in a prerendered page ng build itself failed. So when an SSR page goes missing, look at the server’s terminal, or the build output, first.

There are three fixes, from most to least common:

  1. Run browser-only code in afterNextRender. It never runs on the server. That’s our real last-visit.ts. The server renders Last visit: unknown, and the browser fills in the real value once it has hydrated.
  2. Ask where you are with isPlatformBrowser(inject(PLATFORM_ID)), as Books does, and skip the browser-only part on the server. Use it when the question is whether to do something at all on this platform, not when to do it.
  3. Use inject(DOCUMENT) instead of the global document, as About does. It works in both places.

And if a whole page can’t run on the server, give it RenderMode.Client, as we did for Account. Exercise 2 shows what happens to it on the server.

One thing to avoid in fix 2: don’t use it to render different content on the server and in the browser. Hydration expects the browser’s first render to match the server’s HTML. That’s the next example.

Worked example: a hydration mismatch

The first version of our About page had a table without <tbody>, part of about.ts:

    <table>
      <tr>
        <td>Books</td>
        <td>rendered on the server for every request</td>
      </tr>

It builds. It even looks right. But on a development build, the browser console shows this error on /about (we’ve left out a closing note and the stack trace):

ERROR RuntimeError: NG0500: During hydration Angular expected <tr> but found <tbody>.

Angular expected this DOM:

<table>
  <tr>…</tr>  <-- AT THIS LOCATION
  …
</table>

Actual DOM is:

<table>
  <tbody>…</tbody>  <-- AT THIS LOCATION
</table>

Note: attributes are only displayed to better represent the DOM but have no effect on hydration mismatches.

To fix this problem:
  * check the "_About" component for hydration-related issues
  * check to see if your template has valid HTML structure
  * check if there are any third-party scripts that manipulate the DOM. More info: https://v22.angular.dev/guide/hydration#third-party-scripts-with-dom-manipulation
  * or skip hydration by adding the `ngSkipHydration` attribute to its host node in a template

NG0500 is a hydration mismatch: the DOM in the browser isn’t the DOM the server sent. Here’s how that happened. The server wrote <table><tr>, as the template says. The browser’s HTML parser read that and quietly added a <tbody>, because in HTML, table rows always sit in one. Then hydration walked the DOM, expected a <tr>, and found a <tbody>.

A production build reports only ERROR D: NG0502, a code (with a different number) and no explanation.

The message points at the fix: “check to see if your template has valid HTML structure”. Add the <tbody>, as in the about.ts above, and the error is gone.

The other usual cause is a script or browser extension that changes the DOM behind Angular’s back. ngSkipHydration on a component’s tag makes Angular throw that component’s server HTML away and draw it again. Treat it as a last resort. That component loses everything hydration gave it.

In older code

Before Angular 22, incremental hydration was opt-in: provideClientHydration(withIncrementalHydration()). That function is deprecated now, because it’s the default. Event replay was opt-in too, with withEventReplay(); you’ll still see it in many app.config.ts files. Turn incremental hydration off with withNoIncrementalHydration(); that also turns off event replay, so add withEventReplay() if you want to keep it. Older servers used CommonEngine from @angular/ssr/node, which is deprecated since Angular 22, instead of AngularNodeAppEngine. You’ll also see isPlatformBrowser checks where afterNextRender would do.

Best practices

  • Pick the render mode per route. Prerender for pages that are the same for everyone, Server for pages that change, Client for pages that only make sense signed in. It replaces one rule for the whole app.
  • Put browser-only code in afterNextRender. It’s skipped on the server, and runs after hydration in the browser. It replaces typeof window !== 'undefined' checks scattered through components.
  • Use inject(DOCUMENT), not the global document. It works on the server, and what you add to it ends up in the HTML. It replaces code that only works in the browser.
  • Wrap heavy, below-the-fold parts in @defer with a hydrate trigger. The reader sees them at once, and their code loads only when needed. It replaces hydrating the whole page up front.
  • Load data with HttpClient or httpResource. The server waits for it, and the transfer cache stops the browser asking twice. It replaces raw fetch calls, which the transfer cache doesn’t see.
  • Write valid HTML in templates. Put table rows in a <tbody>. The browser repairs invalid HTML its own way, and hydration then fails. It replaces relying on the browser to tidy up.

Tips and traps

  • localStorage, window or document in a constructor or field. Depending on where it fails, the page is a 404 (Cannot GET /), a 500, or, for a prerendered route, ng build fails. The server’s terminal (or the build output) says ReferenceError: ... is not defined. Move the code to afterNextRender, or use inject(DOCUMENT).
  • The built server refuses localhost. Header "host" with value "localhost:4000" is not allowed. Add the host to security.allowedHosts in angular.json, and your real domain before you deploy.
  • No chunk download for a @defer block in ng serve. With HMR on, the dev server loads every block’s code up front and prints NG0751. Use ng serve --no-hmr or the built server to watch the chunk load.
  • Different content on the server and in the browser. A clock, a random number, or an isPlatformBrowser branch in the template. The page changes the moment the browser takes over, which looks like a flicker, or, if the elements differ, you get NG0500. Render the same thing in both places, and change it in afterNextRender.
  • A request made twice. The Network tab shows a request the server already made. Make it with HttpClient or httpResource, check that it’s a GET, and check you haven’t added withNoHttpTransferCache().

The server sends a page you can read; hydration makes it one you can use, a piece at a time.

Exercises

Exercise 1. Without running it: on the Books page, which of these run on the server, which in the browser, and which in both? The Books constructor; LastVisit‘s afterNextRender; LikeButton‘s afterNextRender, before anyone clicks.

Exercise 2. Account reads localStorage in a field, and it works. Why? What happens if you remove its line from app.routes.server.ts, so that '**' gives it RenderMode.Server?

Exercise 3. Change the Books template to @defer (hydrate never). Load / and click the like button. What does it show? Is the like-button chunk loaded?

Answers

1. The Books constructor runs in both. The server’s terminal shows Books created on the server, and the browser console shows Books created on the browser. LastVisit‘s afterNextRender runs only in the browser: the server’s HTML says Last visit: unknown, and after hydration the page says Last visit: first time here. LikeButton‘s afterNextRender runs nowhere until the click, because its code isn’t loaded. After the click, the console shows LikeButton is running in the browser.

2. It works because RenderMode.Client means Account never runs on the server. Here’s app.routes.server.ts without its line:

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

export const serverRoutes: ServerRoute[] = [
  { path: 'about', renderMode: RenderMode.Prerender },
  { path: '**', renderMode: RenderMode.Server },
];

Now /account is rendered on the server. On a development build, the browser gets a 404 with Cannot GET /account, and the server’s terminal shows:

ERROR ReferenceError: localStorage is not defined
    at <instance_members_initializer> (dist/ssr-demo/server/main.server.mjs:18414:52)

followed by a line at new _Account. To render it on the server, move the read into afterNextRender, as LastVisit does.

3. The template’s @defer line becomes:

    @defer (hydrate never) {

The button still shows Likes: 0 after the click, and the like-button chunk is never loaded. The block is never hydrated, so nothing listens to the click. The console has no errors. This is on a page that came from the server; after a navigation inside the app, the block would use its normal trigger instead. hydrate never suits content that never needs code in the browser, like a long article inside an otherwise interactive page.

What’s next

We’ve now seen each piece of a modern Angular app on its own. In Part 30, we’ll put them together in one reading-list app with routes, Signal Forms, httpResource, a store and tests.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.