Sub topic 4
Enabling hydration and what it reuses
This chapter assumes you can build standalone Angular components and configure an app with ApplicationConfig. It also assumes you have already added SSR to a project with the CLI, as covered in the previous chapters. Here you will enable hydration, learn what Angular carries over from the server-rendered page, and learn what it rebuilds.
The problem hydration solves
A server-rendered page arrives in the browser as finished HTML, so the user sees content quickly. That HTML is static, though. No Angular code is running, so no click handlers, bindings, or component instances exist yet.
Once the JavaScript bundle loads, Angular has to take over. Without hydration, Angular does this the blunt way. It bootstraps the application, destroys the server-rendered DOM, and renders everything again from scratch. The user sees a visible flicker, and the browser repeats work the server already did. Layout shifts can hurt Core Web Vitals scores such as Largest Contentful Paint (LCP) and Cumulative Layout Shift (CLS).
Hydration removes the rebuild. Angular walks the existing DOM, attaches itself to the nodes that are already there, and wires up listeners and bindings. The page does not flicker, because the elements the user was looking at stay in place.
Enabling hydration
Hydration is a browser-side feature, so you enable it in the shared application config with provideClientHydration. The config below is the one the CLI generates for a project with SSR.
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
provideClientHydration(withEventReplay()),
],
};Three details matter here:
provideClientHydration()is the single switch. Called with no arguments, it enables basic hydration. Features are passed as arguments, such aswithEventReplay(), which a later chapter covers.withFetch()switchesHttpClientto thefetchAPI. Angular recommends this for SSR because it works well in server runtimes.- The config is shared. The server config merges this config with its own providers, so hydration providers are present on both sides. The server uses them to write extra information into the HTML. The browser uses the same information to hydrate.
The entry point in main.ts stays an ordinary bootstrap call. Nothing special is required, because hydration is turned on by the providers.
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));If you add provideClientHydration to an app that has no server rendering, there is no server DOM to reuse. Angular falls back to normal client rendering and logs a warning in development mode. So the provider helps only when the page really was rendered on the server.
What the server adds to the HTML
Plain HTML does not say which Angular component produced which element, or where an @if block starts and ends. The server therefore adds hints while it renders.
- Component host elements receive an
nghattribute. Its value is an index into a serialized table of per-view information. - That table is stored in a script tag, which also holds the transfer state described in a later chapter. It records how many nodes each view contains, which nodes are containers for control flow such as
@ifand@for, and similar facts. - The root element receives an
ng-server-contextattribute, such asssrorssg. It records how the page was produced. - Control flow and other dynamic containers appear as comment nodes in the output, which gives the browser anchor points in the DOM.
You can see all of this in your browser's "View Source" for a server-rendered page. The ngh attributes are the visible evidence that the server prepared the HTML for hydration.
The following diagram shows the order of events.
How Angular matches the DOM
On the browser side, Angular runs your components again. It creates the component instances, evaluates the templates, and decides which nodes each template needs. Instead of creating those nodes, it looks for them in the existing DOM. It uses the ngh hints to find the first node of each view and then advances through siblings in step with the template.
This has a consequence. The DOM that the server produced must have the same structure as what the template would create in the browser. If Angular expects a <div> and finds a <p>, it cannot claim the node. It reports a hydration mismatch error such as NG0500, and the affected content is rendered again. A later chapter covers the causes and fixes.
After the application becomes stable, Angular also runs a cleanup step. Any server-rendered nodes that no view claimed are removed. Typical examples are content for views that were never hydrated, such as deferred blocks that have not been activated.
What gets reused and what does not
Hydration reuses the structure. It does not reuse the running state of the server application.
| Item | Reused from the server? | Notes |
|---|---|---|
| DOM elements and text nodes | Yes | Angular claims them instead of creating new ones. |
| Component host elements | Yes | Matched using the `ngh` attribute. |
| Control flow structure | Yes | `@if`, `@for`, and `@switch` containers are located through comment anchors. |
| Component instances | No | The browser constructs every component again. |
| Signals, fields, and service state | No | They start from their initial values in the browser. |
| Event listeners and bindings | No | Angular attaches them during hydration. |
| HTTP responses | Only if transferred | The HTTP transfer cache replays them. |
| Timers and subscriptions | No | They exist only in the process that created them. |
The distinction between structure and state is the most important idea in this chapter. The server and the browser each run their own copy of the application. The server's copy produces HTML and then ends. The browser's copy starts fresh, and hydration lets it adopt the server's DOM.
Consider this component.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<button (click)="increment()">Clicked {{ count() }} times</button>
`,
})
export class CounterComponent {
count = signal(0);
constructor() {
console.log('CounterComponent constructed');
}
increment() {
this.count.update((n) => n + 1);
}
}The constructor runs twice: once in the server process, where the log appears in the terminal, and once in the browser console. The server renders Clicked 0 times. The browser constructs its own component with count at 0, claims the existing <button>, and attaches the click listener. The click listener is the only part that was missing before. The button text was already correct.
This also explains a common mistake. If a component computes a value on the server that cannot be recomputed in the browser, such as a random number, the two sides disagree. The browser's value then replaces the server text. Data that the browser must see identically has to be handed over explicitly through the transfer mechanisms in a later chapter.
Confirming that hydration works
Check three things after enabling it.
- Run the production-like server build and open the page. In development mode, the browser console prints a message stating that Angular hydrated some number of components and nodes. If the message is absent, hydration is not active.
- View the page source and look for
nghattributes on component hosts. Their presence shows that the server has hydration enabled. - Watch the page load with network throttling. The content should stay in place and not blink when the JavaScript finishes loading.
You can also inspect the DOM in developer tools. Angular DevTools shows which components were hydrated and flags any that hit a mismatch.
Run the SSR server, not only ng serve against a client-only build. With the CLI setup from the earlier chapter, ng serve already renders on the server in development. Build with ng build and start the Node server output if you want to check production behavior.
Trade-offs of enabling hydration
Hydration is not free.
- The HTML carries extra data: the
nghattributes and the serialized view table. This adds to the payload, though the cost is small compared with the cost of full re-rendering. - Components that change the DOM directly, outside Angular's templates, may break the match. The constraints chapter covers these.
- The browser still downloads and runs all the JavaScript before the page becomes interactive. Hydration saves rendering work and removes flicker. It does not remove the bundle cost. Event replay and incremental hydration, later in this tutorial, address interactivity before and during hydration.
Quick reference
- Enable hydration with
provideClientHydration()in the sharedApplicationConfig. - The server writes
nghattributes and a serialized view table. The browser uses them to match components to DOM nodes. - Angular reuses DOM nodes and structure. It rebuilds component instances, state, listeners, and bindings.
- Unclaimed server nodes are cleaned up after the app stabilizes.
- A structural difference between server and browser output produces an
NG05xxerror and a re-render of the affected part.
Exercise
A component keeps a visits = signal(0) field and increments it in a server-side ngOnInit before the page is rendered, so the server HTML shows Visits: 1. After hydration, the browser shows Visits: 0 for a moment, then the text changes. Why does this happen, and what does hydration reuse here?
Show answer
Hydration reuses the DOM nodes, including the text node, but not the component instance or its signals. The browser constructs a new component whose visits starts at 0, so its binding evaluates to 0 and replaces the server text. To keep the value 1 on both sides, the server value has to be passed to the browser explicitly, for example with TransferState, or the state must be derived from data both sides can compute.
Exercise
You enabled provideClientHydration() but the console never reports hydrated components, and View Source shows no ngh attributes. Name two likely causes.
Show answer
The page may not be server rendered at all, for example because the app is served as a client-only build, so there is no server DOM to hydrate. Alternatively, the server config may not include the shared application config, so the hydration providers are missing on the server side and no hints are written. Checking that mergeApplicationConfig(appConfig, serverConfig) is used on the server is the first step.