Muhammed Senussi
Muhammed Senussi
  • Muhammed Senussi
Hydration Mismatches and How to Actually Find Them
Angular

Hydration is a promise that the client will reuse the server’s DOM. Break the promise and Angular has to recover, and the recovery is rarely what you wanted.

The usual causes

  • Reading window, localStorage or document.location during construction. The server has no equivalent, so it renders a different branch.
  • Dates and random values. new Date() on the server and on the client are two different times.
  • Direct DOM manipulation in ngOnInit, which the server never performed.
  • Content that depends on a request that resolved on the server but not yet on the client — the fix is the transfer cache.

Finding them

The console warnings tell you the component but not always the reason. What worked for me was instrumenting history.replaceState to capture a stack trace: a route that reverts to the home page is the router rolling back after a mismatch, and the stack shows you which navigation triggered it.

The most valuable habit is to diff the server HTML against the first client render for a page you suspect. Save both and compare — the difference is your bug, stated exactly.

2 Comments

  • Sanne de Vries

    September 10, 2024

    Instrumenting replaceState to get a stack trace is a great trick. A route silently reverting is such a confusing symptom.

    • Muhammed Senussi

      Muhammed Senussi

      AuthorSeptember 10, 2024

      It confused me for most of a day. The page looked like a routing configuration problem, and every routing configuration I checked was correct — because the routing was fine and the rollback was a symptom of something else entirely.

Leave a comment