Sub topic 8
Hydration constraints and diagnosing mismatches
This chapter assumes you have enabled hydration with provideClientHydration and can run an SSR build with the Angular CLI. It also assumes you know basic HTML nesting rules and can read browser DevTools output.
Why hydration has constraints
Hydration does not rebuild the page. When the browser loads the server HTML, Angular walks the component tree and attaches each component, binding, and listener to a DOM node that already exists. To do this, it needs a compact description of how the server DOM was built. The server writes that description into ngh attributes on component host elements, and the client reads them.
This means the DOM the browser holds at hydration time must have the same structure as the DOM Angular would have created on its own. If it doesn't, Angular can't match nodes to the component tree. It then reports a mismatch error, and in some cases it discards the server DOM and renders the affected part again.
Two terms matter here:
- A structural mismatch is a difference in which nodes exist, their types, or their order. This is what hydration checks.
- A value difference is a difference in text or attribute values on nodes that otherwise line up. Angular does not compare these. It reuses the node and updates it, which can cause a visible flicker but no error.
The main causes of mismatches
Most mismatches come from one of four sources.
1. HTML the browser rewrites
The server serializes its DOM to a string. The browser then parses that string with the HTML parser, which fixes invalid markup. After parsing, the browser DOM can differ from what Angular generated on the server.
Common cases:
- A block element such as
<div>or<ul>inside a<p>. The parser closes the<p>early. - A
<table>with<tr>children but no<tbody>. The parser inserts a<tbody>. - An
<a>inside another<a>. - A
<button>inside another<button>, or a<form>inside a<form>.
This component breaks hydration:
import { Component } from '@angular/core';
@Component({
selector: 'app-price-table',
template: `
<p>
Prices
<div class="note">All prices include tax.</div>
</p>
<table>
<tr><td>Basic</td><td>10</td></tr>
</table>
`,
})
export class PriceTableComponent {}On the client, Angular expects a <p> that contains a <div>, but the parsed DOM has an empty <p> after the <div>. It also expects <tr> directly under <table>, while the browser inserted a <tbody>. The fix is valid markup:
import { Component } from '@angular/core';
@Component({
selector: 'app-price-table',
template: `
<div>
<p>Prices</p>
<div class="note">All prices include tax.</div>
</div>
<table>
<tbody>
<tr><td>Basic</td><td>10</td></tr>
</tbody>
</table>
`,
})
export class PriceTableComponent {}2. Direct DOM manipulation
Code that creates, moves, or removes nodes outside Angular's templates changes the DOM without Angular knowing. On the server, this code runs against the server DOM implementation and its changes are serialized. On the client, it may run before or after hydration and produce a different tree.
Typical culprits are ElementRef.nativeElement.innerHTML = ..., appendChild, insertBefore, document.createElement, and third-party libraries that build DOM, such as chart, editor, or map widgets.
import { Component, ElementRef, inject } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label">New</span>`,
})
export class BadgeComponent {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
// Bad: edits the host DOM during construction, on server and client.
this.el.nativeElement.insertAdjacentHTML('beforeend', '<i class="star"></i>');
}
}The fix is to let the template own the markup. If the content comes from a string, use [innerHTML], which Angular sanitizes. If a library must touch the DOM, create it only in the browser with afterNextRender, and put it in an element Angular does not manage:
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label">New</span><span #extra></span>`,
})
export class BadgeComponent {
private extra = viewChild.required<ElementRef<HTMLElement>>('extra');
constructor() {
afterNextRender(() => {
this.extra().nativeElement.innerHTML = '<i class="star"></i>';
});
}
}The empty <span #extra> exists on both sides. The browser-only code fills it after hydration has finished.
3. Different structure on server and client
If a template renders different elements depending on the platform, the two trees diverge. A template that branches on isPlatformBrowser is the usual cause.
@if (isBrowser) {
<app-live-chart />
} @else {
<p>Loading chart...</p>
}This pattern is risky because the server and the first client render disagree about which branch exists. Prefer a state that is the same on both sides at first and changes only after hydration:
import { Component, afterNextRender, signal } from '@angular/core';
@Component({
selector: 'app-chart-slot',
template: `
@if (ready()) {
<app-live-chart />
} @else {
<p>Loading chart...</p>
}
`,
})
export class ChartSlotComponent {
protected ready = signal(false);
constructor() {
afterNextRender(() => this.ready.set(true));
}
}Both server and client start with ready() === false, so the initial trees match. The signal flips only in the browser, after hydration, and Angular updates the DOM normally.
Values that differ between runs, such as Date.now(), Math.random(), or a locale-dependent format, are a milder version of this problem. They do not throw, but the user sees the text change on load. Compute them in afterNextRender, or pass the server's value to the browser with TransferState.
4. HTML changed between server and browser
Anything between your server and the user's browser that edits the HTML can break the match. Angular relies on comment nodes as anchors for control flow and containers. CDN or proxy features that minify HTML, strip comments, or inject scripts can remove or alter nodes. Check these settings first when hydration works locally and fails in production.
Reading the error codes
In development mode, Angular logs hydration errors with the component name and, for node mismatches, the expected and actual nodes along with their DOM path. Production builds keep only the error code. The codes below are the ones you will meet most often. Look up the full text for any code on the Angular error reference page.
| Code | Meaning | Usual cause |
|---|---|---|
| NG0500 | Node mismatch: Angular expected one element and found another | Invalid HTML nesting, DOM edited outside Angular |
| NG0501 | Missing siblings: Angular expected more nodes than exist | Nodes removed by DOM code, a proxy, or a parser fix |
| NG0502 | Missing node: an expected node was not found | Comment nodes stripped, DOM changed before hydration |
| NG0503 | Unsupported projection of DOM nodes | Content projected in a way hydration cannot track |
| NG0504 | `ngSkipHydration` placed on an invalid node | Attribute set on a plain element instead of a component host |
| NG0505 | No hydration information in the server response | Page served without SSR, or `ngh` attributes stripped |
| NG0506 | The application did not become stable within 10 seconds | Pending timers or HTTP calls during server rendering |
| NG0507 | HTML was altered after server rendering | CDN or proxy rewriting the HTML |
NG0506 deserves a note. The server waits for the app to become stable before it serializes. A setInterval, a long setTimeout, or a request that never finishes keeps the app unstable, so the page is never captured. Run recurring timers only in the browser, inside afterNextRender.
A diagnosis workflow
Work from the cheapest check to the most expensive.
- Confirm hydration ran. Open the browser console in development mode. A message such as "Angular hydrated N component(s) and M node(s)" confirms it. The same message reports how many components were skipped.
- Read the first error only. One bad node often causes several later errors. Fix the first one and rebuild before reading the rest.
- Find the component. The dev-mode message names the component and gives a DOM path. Open that component's template and look for the elements in that region.
- Compare the two DOMs. Fetch the raw server HTML with
curlor "View Source", which shows what the server sent. Then compare it with the Elements panel in DevTools, which shows what the browser built. Differences such as an inserted<tbody>or a split<p>show up here. - Check
nghattributes. Raw HTML with nonghattributes means the response did not come from the SSR render, or something removed them. - Search for DOM access. Look in the component and in directives it uses for
nativeElement,innerHTML,document.,Renderer2calls that create nodes in constructors, and third-party widgets. - Validate the markup. Run the template's rendered HTML through an HTML validator, or review nesting by eye.
When you cannot fix the cause
Some components, usually third-party ones, manipulate the DOM in ways you cannot change. For those, mark the component host with ngSkipHydration. Angular then discards its server DOM and renders it fresh in the browser. The next chapter covers this in detail. Use it only after you have ruled out the causes above, because the skipped component loses the benefit of reuse and may flicker on load.
Exercises
Exercise
A component's template contains <p>Details <ul><li>One</li></ul></p>. The page renders correctly with SSR but the console shows an NG0500 node mismatch in development mode. Why does this happen, and how do you fix it?
Show answer
The server serializes the DOM Angular built, with a <ul> inside the <p>. The browser's HTML parser does not allow a <ul> inside a <p>, so it closes the <p> before the <ul>. The browser DOM then has a different structure than Angular expects, which causes the mismatch. Fix it by using valid markup, for example wrapping the content in a <div> and putting the text in its own <p>, so the nesting survives parsing.
Exercise
A component shows {{ now }} where now is set to new Date().toLocaleTimeString() in the constructor. Hydration reports no error, but users see the time change right after load. Why is there no error, and how would you remove the flicker?
Show answer
Hydration checks structure, not text values. The text node exists on both sides, so Angular reuses it and updates the text, which produces the visible change. To remove the flicker, make the initial value identical on both sides, for example an empty or placeholder string held in a signal, and set the real time inside afterNextRender so it appears only in the browser. Alternatively, compute the value on the server and pass it to the browser with TransferState.
Exercise
Hydration works with ng serve but the deployed site logs NG0507 and some pages log NG0505. Which part of the system do you inspect first, and what do you compare?
Show answer
Inspect whatever sits between the Node server and the browser, such as a CDN or reverse proxy. Fetch the raw HTML from the deployed site and compare it with the HTML the Node server returns directly. Look for removed comment nodes, minified or rewritten markup, injected tags, or missing ngh attributes. Then turn off HTML rewriting features for those routes.