← Back to Angular, page 8

angular-0145 · Hard senior

What is hydration in Angular server-side rendering, what causes hydration mismatch errors, and how do you debug and fix them?

Hydration reuses the server's HTML instead of rebuilding the DOM. Angular walks the existing DOM and matches it to the component tree. A mismatch happens when the server and browser structures differ, usually because of invalid HTML nesting, direct DOM changes, or browser-only values rendered during server rendering. Fix the cause, or use ngSkipHydration for a component as a last resort.

Full answer

Without hydration, the browser shows server HTML and then Angular destroys it and renders again, causing a flash and wasted work. With provideClientHydration(), Angular attaches to the existing DOM nodes, restores state (TransferState for HTTP responses), and makes the page interactive. Angular 19 and later add incremental hydration with @defer (hydrate on viewport), and event replay so clicks before hydration are not lost (withEventReplay()).

How matching works: Angular serializes structure hints in the server HTML (ngh attributes). In the browser, it expects the DOM to have the same nodes in the same order. If a node is missing or different, it throws an error such as NG0500 to NG0502, or NG0503, with a message that names the expected and found nodes.

Common causes:

  1. Invalid HTML nesting, such as a div inside a p or a table without tbody. The browser parser fixes the HTML and changes the structure before Angular sees it.
  2. Direct DOM manipulation (innerHTML, appendChild, document.createElement) in components, or a library that changes the DOM during server rendering. Use renderer APIs or move DOM code to afterNextRender, which runs only in the browser.
  3. Different output on server and client: Date.now(), Math.random(), window.innerWidth, or localStorage read while rendering. The server and browser values differ, so the text or structure differs. Use afterNextRender for browser-only values, or serialize one value with TransferState.
  4. Whitespace changes (preserveWhitespaces) or a CDN that modifies or minifies HTML (for example removing comments, which Angular uses as markers). Disable HTML minification of comments at the edge.
  5. Third-party components that are not hydration safe. Add ngSkipHydration to that component host: <app-chart ngSkipHydration />. It re-renders that subtree only.

Debugging steps:

  • Read the error message: it names the component and the DOM node. Check the HTML in "View Source" (server output) against the DOM after load.
  • Run in development mode, where hydration validates more.
  • Angular DevTools shows hydration status (the overlay highlights hydrated components).
  • Isolate by removing the suspicious component or adding ngSkipHydration temporarily, then fix the real cause.
  • Log isPlatformServer branches that render different content.

Rule: render the same thing on the server and in the first browser pass, and add browser-only differences afterwards.

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

@Component({
  selector: 'app-viewport-info',
  template: `<p>Screen width: {{ width() ?? 'unknown' }}</p>`,
})
export class ViewportInfoComponent {
  // Same value on server and in the first browser render, so hydration matches.
  readonly width = signal<number | null>(null);

  constructor() {
    // Runs only in the browser, after hydration. The DOM updates normally.
    afterNextRender(() => this.width.set(window.innerWidth));
  }
}

// app.config.ts: provideClientHydration(withEventReplay())
// Risky version: {{ innerWidth }} during rendering gives different text on server and browser.

Angular 20.3, type-checked. Server rendering was not run here, so no mismatch was reproduced. The sample shows the safe pattern for browser-only values.

Key points

  • Hydration reuses server DOM instead of rebuilding it, with event replay and incremental hydration options.
  • Mismatches come from invalid HTML, direct DOM changes, and server or client differences.
  • Move browser-only work to `afterNextRender`. Use `TransferState` for shared values.
  • `ngSkipHydration` is a last resort for a component.

Common mistakes

  • Reading `window` or `localStorage` while rendering on the server.
  • Using `ngSkipHydration` everywhere instead of fixing causes.
  • Letting a CDN strip HTML comments that Angular needs.

Follow-ups

  • What does event replay solve?
  • How does `@defer (hydrate on viewport)` reduce work?
  • How would you pass a value from server to browser without a second request?

Tips

  • List the causes in the order you would check them.
  • Mention View Source versus DOM as the first debugging step.
  • Describe `ngSkipHydration` as a temporary tool.

Evaluation rubric

  • Explains hydration and what it saves.
  • Lists realistic mismatch causes.
  • Gives a debugging process and clean fixes.