My account

SSR and hydration in Angular

With server-side rendering, the server sends ready HTML, so the product page shows fast and search engines can read it. Hydration then makes that HTML alive in the browser without drawing it again. You must know what can break it (browser-only code, different data on server and client, direct DOM changes), how event replay keeps early clicks, and how incremental hydration and render modes keep the JavaScript small.

Not reviewedWritten with AI helpReading time: 16 minOnline shop exampleAngular 20 code

Author: bezzad

Contents

The problem: an empty page for Google and for phones

Our shop is a normal Angular app (client-side rendering). The server sends an almost empty index.html and a big JavaScript file. Then:

  1. On a slow phone, the product page is white for 3 seconds, until the JavaScript is downloaded and has run.
  2. Link previews in chat apps show no title and no image, because their bots do not run JavaScript.
  3. Search ranking is weak for product pages.

Server-side rendering (SSR) fixes this. But it brings new kinds of bugs.

How SSR and hydration work

No SSRwhite page: download and run JSvisible + works3.0 sSSRHTMLvisible, JS loadinghydrated: works0.8 s2.4 sclick at 1.5 sreplayed after hydration
With SSR, the page is visible as soon as the HTML arrives. It becomes interactive after hydration. With event replay, a click before that moment is not lost.
  1. On the server, Angular runs the app for the URL, waits for the HTTP calls, and sends full HTML.
  2. In the browser, the user sees the page at once. The JavaScript downloads in the background.
  3. Hydration: Angular starts, walks the existing DOM and connects it to the components. It reuses the DOM nodes, it does not destroy and draw them again. So there is no flicker.
  4. Until hydration ends, buttons do not work. Event replay records clicks and key presses in that time and runs them after hydration.
// a new project: ng new shop --ssr (or ng add @angular/ssr)
// app.config.ts
import {
  provideClientHydration, withEventReplay, withIncrementalHydration,
} from '@angular/platform-browser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withFetch()),
    provideClientHydration(withEventReplay(), withIncrementalHydration()),
  ],
};

No double requests: the HTTP transfer cache

The server already called /api/products/7. Without help, the browser would call it again during hydration. With provideClientHydration, HttpClient puts the server responses into the HTML, and the browser uses them on the first load.

  1. By default it caches GET and HEAD requests.
  2. Requests with an Authorization header are not cached by default, so private data does not land in the HTML.
  3. This only works with HttpClient. A plain fetch call runs twice.

Code that only works in the browser

On the server there is no window, no document, no localStorage and no real screen size. Code that touches them during render fails on the server.

export class PriceTag {
  // Bad: crashes on the server, localStorage is not defined.
  // currency = localStorage.getItem('currency') ?? 'EUR';

  currency = signal('EUR');

  constructor() {
    afterNextRender(() => {
      // Runs only in the browser, after the first render.
      const saved = localStorage.getItem('currency');
      if (saved) this.currency.set(saved);
    });
  }
}
  1. afterNextRender and afterEveryRender run only in the browser. Use them for localStorage, measuring elements, and third-party widgets.
  2. isPlatformBrowser(inject(PLATFORM_ID)) tells you where the code runs. Use it rarely. Many branches make the server and the browser render different things.
  3. If the server must know the value (so the first HTML already has the right currency), keep it in a cookie. On the server, read it from the request. Angular 19 and newer have a REQUEST token for this.

Hydration mismatch

Hydration expects the browser to build the same DOM as the server. When it does not, Angular shows an error (NG0500 family) in development, and may draw that part again.

Common causes:

  1. Different data: Date.now(), Math.random(), the user’s time zone or language used during render.
  2. Direct DOM changes with innerHTML, document.createElement or a jQuery plugin. Angular does not know about those nodes.
  3. Invalid HTML, like a div inside a p, or a table without tbody. The browser fixes the HTML, so its DOM differs from what the server meant.
  4. A CDN or proxy that changes the HTML, for example by removing comments. Angular uses comment nodes and an ngh attribute for hydration.

For a component you cannot fix now, add the ngSkipHydration attribute on its host. Angular then draws it again on the client. This is a way out, not a solution.

Incremental hydration: wake parts only when needed

header + cartproduct details + buy button@defer reviews@defer size chartfooterhydrated at starthydrated at starthydrate on viewportJS when it is seenhydrate on interactionJS on first clickhydrate never
With incremental hydration, the server sends the whole page as HTML, but the browser downloads and hydrates each @defer part only when its trigger fires. The JavaScript at start is much smaller.
<app-product-details [product]="product()" />

@defer (hydrate on viewport) {
  <app-reviews [productId]="product().id" />
}

@defer (hydrate on interaction) {
  <app-size-chart />
}
  1. The reviews are in the server HTML, so Google and the user see them. But their JavaScript loads only when they come into view.
  2. hydrate on interaction waits for a click or key press, and event replay runs that first click.
  3. hydrate never keeps a part as plain HTML forever. Good for a static footer.
  4. You need withIncrementalHydration() in the providers.

Render modes per route

// app.routes.server.ts
export const serverRoutes: ServerRoute[] = [
  { path: '', renderMode: RenderMode.Prerender },
  { path: 'products/:id', renderMode: RenderMode.Server },
  { path: 'account/**', renderMode: RenderMode.Client },
  { path: '**', renderMode: RenderMode.Server },
];
  1. Prerender (SSG): HTML is built once at build time. Fastest, but the same for everyone. Good for the home page and help pages.
  2. Server: HTML is built on each request. Good for product pages with live prices and stock.
  3. Client: no SSR. Good for private pages behind login, where SEO does not matter.

Common mistakes

Mistake Result Better way
localStorage or window in a constructor The server crashes or the page is empty. afterNextRender, or a cookie read on the server.
Date.now() or random values in a template Hydration mismatch. Make the value on the server and send it, or set it after render.
Plain fetch instead of HttpClient Every request runs twice. HttpClient with the transfer cache.
innerHTML or jQuery on the DOM Mismatch, broken parts. Templates and Renderer, or ngSkipHydration for now.
SSR for private pages Slower server, no SEO win. RenderMode.Client for them.
Hydrating the whole page at once Big JavaScript at start. @defer with hydrate triggers.

Summary in 6 lines

  1. SSR sends ready HTML: fast first view, good SEO and link previews.
  2. Hydration reuses the server DOM. Event replay keeps clicks made before it ends.
  3. HttpClient’s transfer cache stops double requests. Private requests are not cached.
  4. Browser-only code goes in afterNextRender. Values the server needs go in cookies.
  5. Mismatch comes from different data, direct DOM changes and invalid HTML.
  6. Incremental hydration and render modes keep the start JavaScript small.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.