Skip to content

SSR and Hydration

A client-rendered Angular application sends the browser a near-empty HTML shell; nothing is visible, and nothing is reliably indexable, until the JavaScript has downloaded and run. Angular has two ways to send real HTML instead: server-side rendering (SSR), which renders each request on a server, and prerendering (SSG), which renders pages once at build time. Which one fits depends on whether the page’s content is known at build time — the trade-off this page walks through. SSR is also the change most likely to break an application in ways that never appear locally, because it introduces a second execution environment where window does not exist, top-level state is shared between users, and any mismatch between what the server rendered and what the client expects becomes a visible error.

The good news is that the failure modes are a short, well-defined list. Most of this page is that list.

  • CSR — client-side rendering. The server sends a near-empty HTML shell; the browser does everything.
  • SSR — server-side rendering. The server runs the application per request and sends populated HTML.
  • SSG / prerendering — HTML generated at build time, served as static files.
  • Hybrid rendering — choosing among the three per route.
  • Hydration — the client attaching Angular to the server-rendered DOM instead of rebuilding it.
  • Incremental hydration — leaving sections dehydrated and hydrating them on a trigger.
  • Event replay — capturing interactions before hydration and replaying them afterwards.
  • Transfer cache — server-fetched HTTP responses serialised into the HTML so the client does not refetch.
  • Stability — the point at which Angular considers pending async work complete.

Angular lets you set a RenderMode per server route, which means the decision is per screen rather than per application.

CSR SSR Prerender (SSG)
HTML produced In the browser Per request, on the server At build time
First paint Slowest Fast Fastest
SEO Weakest — crawlers limit JS execution Excellent Excellent
Per-user content Yes Yes No
Server cost Static assets only Angular runs per request None at request time
Build time Unaffected Unaffected Grows with page count
Cacheable by CDN Assets only Depends Completely

The honest characterisation of each:

CSR has the simplest development model — you can assume a browser and use any browser-dependent library. It generally performs worst, because nothing is visible until the JavaScript downloads, parses and executes, and any data fetched during render adds further round trips. It is the right choice for authenticated application screens behind a login, where SEO is irrelevant and server cost matters.

SSR eliminates the wait for JavaScript and lets you fetch data during server rendering, removing browser round trips. It costs you: your code must not depend strictly on browser APIs, your library choices narrow, and the server runs Angular for every request.

Prerendering is fastest and cheapest at request time — static HTML, trivially CDN-cacheable, deployable without a server runtime at all. The constraint is absolute: everything needed to render must be known at build time, so prerendered pages cannot contain anything specific to the user loading them. It also lengthens builds, and getPrerenderParams producing many documents inflates deployment size.

A typical hybrid split: prerender marketing and documentation, SSR product and category pages that need SEO and live data, CSR the authenticated dashboard.

One interaction worth knowing: with the Angular service worker, the first request is server-rendered and every subsequent request is handled by the service worker and rendered client-side.

Without hydration, a server-rendered Angular application destroys the server-rendered DOM and rebuilds it — producing a visible flicker, a layout shift, and worse Core Web Vitals than you would expect from SSR. Hydration instead matches existing DOM nodes to the application’s structure and reuses them.

bootstrapApplication(App, {
providers: [provideClientHydration()],
});

The same providers must be used on the server bootstrap. In a default ng new layout that follows automatically; in a custom setup it is a step people miss, and the symptom is hydration silently not happening.

If you enabled SSR through the CLI (ng add @angular/ssr or at project creation), hydration is already wired up.

Verifying it: in development, the console logs hydration statistics — components and nodes hydrated. Angular DevTools shows per-component hydration status and can overlay which parts of the page were hydrated, and it highlights the component responsible for a mismatch error.

Hydration requires the same generated DOM structure on server and client — including whitespace and the comment nodes Angular emits. The HTML produced by server rendering must not be altered between server and client.

That last sentence rules out a category of infrastructure people forget about: HTML minifiers in a proxy, tag-injecting CDNs, and “optimisation” layers that rewrite markup will all break hydration.

Direct DOM manipulation is the most common cause of failure. Accessing document, querying for elements, appendChild, innerHTML/outerHTML, detaching and moving nodes — Angular does not know about any of it, so the structure it finds is not the structure it expects. Refactor to Angular constructs where you can.

Invalid HTML breaks hydration too, because browsers silently repair it and the repaired DOM no longer matches. The common cases:

  • <table> without <tbody> — browsers insert one. Always declare <tbody> explicitly.
  • <div> inside <p>
  • <a> inside <a>

A syntax validator is a quick way to rule this out.

preserveWhitespaces should stay at its default false. Setting it to true is not a fully supported configuration with hydration, and — critically — the value must be consistent between tsconfig.server.json and tsconfig.app.json. A mismatch breaks hydration. Set it in tsconfig.app.json only, which the server config inherits from.

Custom or noop ZoneJS implementations are not yet fully supported, because hydration relies on the stability signal to know when to serialise on the server and to clean up unclaimed DOM nodes on the client. A different onStable timing serialises too early or cleans up too late.

ngSkipHydration opts a component and its entire subtree out:

<legacy-chart ngSkipHydration />
@Component({ host: { ngSkipHydration: 'true' } })
export class LegacyChart {}

It can only go on a component host node — Angular throws if you put it elsewhere. The component then behaves as if hydration were off: it destroys and re-renders itself.

Angular’s framing is worth keeping: this is a last-resort workaround, and components that break hydration should be treated as bugs to fix. Putting it on the root component disables hydration for the entire application.

Its legitimate uses are third-party libraries that render by manipulating the DOM — D3 charts being the canonical example — where you do not control the implementation.

Server-rendered HTML is visible and clickable before hydration attaches any listeners. Without event replay, a click in that window is simply lost, and the user experiences a page that ignored them.

provideClientHydration(withEventReplay());

Angular captures native browser events (click, mouseover, focusin and so on) before hydration, stores them, and re-invokes them once hydration completes.

Incremental hydration enables event replay automatically — if you have both, withEventReplay() is redundant and can be removed.

Full hydration still ships and executes the whole application. Incremental hydration leaves sections dehydrated and hydrates them on a trigger, producing smaller initial bundles while keeping the experience comparable.

It is enabled by default with provideClientHydration(). Opt out with withNoIncrementalHydration().

The mechanism is @defer with hydrate triggers:

@defer (hydrate on viewport) {
<product-reviews [productId]="id()" />
} @placeholder {
<div class="reviews-skeleton"></div>
}

A hydrate trigger tells Angular to load the block’s dependencies during server rendering and render the main template rather than the placeholder. On the client the dependencies stay deferred and the content stays dehydrated until the trigger fires. Events the user produces in between are queued and replayed.

hydrate on idle, on viewport, on interaction, on hover, on immediate, on timer, plus hydrate when and hydrate never. Multiple triggers separated by ; are OR conditions.

The genuinely new capability: @defer becomes usable above the fold. Previously a @defer block above the fold rendered its placeholder and then swapped in the real content, causing a layout shift. With a hydrate trigger the server renders the real template, so there is no shift — the block is simply not interactive until hydrated.

hydrate never is the interesting one for static content: on the initial, server-rendered load, the server renders the block and the browser never fetches its JavaScript or hydrates it, so it stays static HTML. That makes it a good fit for marketing copy, footers and rendered documentation on pages that are usually entered directly.

Two limits matter:

  • It applies to the initial render only. Hydration is an initial-load optimisation. If the same @defer block is rendered later on the client — for example after an in-app navigation to that page — it uses its ordinary @defer trigger and does fetch its dependencies. Give such blocks a sensible regular trigger, e.g. @defer (on viewport; hydrate never).
  • It saves the block’s JavaScript, not everything. The HTML and CSS are still sent, the Angular runtime still loads for the rest of the page, and hydrate never stops hydration for the whole nested subtree, so nothing inside it can become interactive on that load.

Without it, SSR fetches data on the server to render, then the client refetches exactly the same data to hydrate — every request made twice, and a visible content flash between them.

Angular caches server-side HttpClient requests, serialises them into the initial HTML, and the client reuses them instead of re-requesting. It stops using the cache once the application becomes stable, so post-load requests behave normally.

HEAD and GET requests that do not:

  • Carry Authorization, Proxy-Authorization or Cookie headers.
  • Use withCredentials, or a fetch credentials mode that can send credentials.
  • Carry Cache-Control: no-store, no-cache or private on request or response.
  • Use fetch’s cache: 'no-store' or 'no-cache'.
  • Return a Set-Cookie header.

That default is well chosen: the exclusions are exactly the markers of a per-user or non-cacheable response. The cached values are serialised into the page’s HTML, so a per-user response reaching the transfer cache on a page a CDN caches is a data leak, not just a correctness bug.

Configure it explicitly when needed:

provideClientHydration(
withHttpTransferCacheOptions({
includeHeaders: ['ETag'],
filter: (req) => !req.url.includes('/api/profile'),
}),
);

The same reasoning applies to resource’s id option, which caches into TransferState: use it for shared, cacheable data and leave it off anything user-specific.

With the default fetch backend on the server, Angular limits each response body to 1 MB, failing with NG02825 above that. This prevents the server buffering unexpectedly large responses during rendering. It is raisable:

provideServerRendering({ maxResponseBodySize: 5 * 1024 * 1024 }, withRoutes(serverRoutes));

Angular’s advice is to keep it as small as the application allows, because a larger limit means larger buffers, more memory, and more denial-of-service surface. Move large downloads out of server rendering rather than raising the ceiling.

window, document, navigator, location and much of HTMLElement do not exist on the server.

The recommended solution is not a runtime check. Angular’s guidance is to prefer platform-specific providers over isPlatformBrowser / isPlatformServer:

export abstract class AnalyticsService {
abstract trackEvent(name: string): void;
}
// app.config.ts (browser)
{ provide: AnalyticsService, useClass: BrowserAnalyticsService }
// app.config.server.ts
{ provide: AnalyticsService, useClass: NoopAnalyticsService }

Platform logic lives in one place, the component stays platform-agnostic, and the server bundle never contains the browser implementation.

For browser-only initialisation, use the render hooks, which run on the client only and are skipped on the server:

constructor() {
afterNextRender(() => {
console.log('height:', this.contentRef().nativeElement.scrollHeight);
});
}

Never use isPlatformBrowser in a template to render different content on server and client. Angular calls this out explicitly: it causes hydration mismatches and layout shifts, damaging both user experience and Core Web Vitals. Keep the rendered output identical across platforms and put browser-specific work in afterNextRender.

Server providers are shared between requests

Section titled “Server providers are shared between requests”

A genuinely dangerous subtlety: on the server, top-level provider values are evaluated once when the application code is parsed, and useValue providers keep that value across every request until the process restarts.

A useValue holding request-scoped data — a user, a locale, a token — is therefore shared between users. Use useFactory, which runs per request:

{ provide: REQUEST_CONTEXT, useFactory: () => buildContextFromRequest() }

The same reasoning applies to any module-level mutable state in a service: on the client it is per-user by construction, on the server it is per-process.

Hydration and post-hydration cleanup only run once the application reports stability. Anything keeping async work outstanding delays it: timers, intervals, unresolved promises, pending microtasks. After 10 seconds you get NG0506 — “application remains unstable”.

Under zoneless, Angular cannot infer this; you tell it with PendingTasks:

private readonly pendingTasks = inject(PendingTasks);
await this.pendingTasks.run(async () => {
this.report.set(await this.api.fetchReport());
});

Or pendingUntilEvent() from @angular/core/rxjs-interop for observables. In-flight HttpClient requests and ongoing router navigations already register pending tasks, so those are handled.

To diagnose, provideStabilityDebugging() logs pending tasks when stabilisation takes longer than expected. It is provided by default in development when using provideClientHydration(), and can be added manually for a production bundle or for SSR without hydration. On ZoneJS applications, import 'zone.js/plugins/task-tracking' additionally reports which macrotask is holding the zone open, with the stack trace of its creation.

Angular does not strip the task-tracking plugin or this utility from production bundles, so use them for temporary debugging and take them out again.

i18n: Angular skips hydration for components using i18n blocks by default, re-rendering them from scratch. withI18nSupport() in provideClientHydration() enables hydration for them.

Third-party scripts: ad trackers and analytics that modify the DOM before hydration cause mismatches, because the page no longer matches what Angular expects. Defer them until after hydration — afterNextRender is the hook for it.

SSRF: a server rendering your application can be induced to make requests on an attacker’s behalf. Angular documents allowed-host configuration for this; treat any server-side fetch whose URL derives from request data as a potential SSRF.

Symptom Cause Fix
Flicker / layout shift after load Hydration not enabled or not applied on the server Add provideClientHydration() to both bootstraps
NG0500-class DOM mismatch Direct DOM manipulation, or invalid HTML Refactor to Angular APIs; add <tbody>; validate the HTML
Mismatch only in production A proxy or CDN altering the HTML Disable HTML rewriting between server and client
NG0506 application unstable Timers, intervals, unresolved promises provideStabilityDebugging(); register work with PendingTasks
NG02825 SSR response body over 1 MB Raise maxResponseBodySize, or move the download out of rendering
window is not defined Browser API at construction or in a field initialiser Platform-specific provider, or afterNextRender
Data flashes then reloads Transfer cache not applying Check the request is a GET/HEAD without credential headers
One user sees another’s data useValue provider holding request state Use useFactory
Content differs between server and client isPlatformBrowser in a template Render the same output; move logic to afterNextRender
Clicks before hydration ignored Event replay off withEventReplay(), or rely on incremental hydration
Hydration works but the bundle is unchanged Full hydration only Add hydrate triggers to @defer blocks
Decision Favours Costs
CSR Simplest model, any browser library, cheapest server Slowest first paint, weakest SEO
SSR Fast first paint, excellent SEO, server-side data fetching Server cost; server-compatible code required
Prerender Fastest, CDN-cacheable, no runtime server Build-time data only; longer builds
Hydration No flicker, better CWV Structural constraints; DOM manipulation must go
Incremental hydration Smaller bundles; @defer above the fold Hydration boundaries to design
hydrate never The block’s JavaScript is not fetched on the initial server-rendered load Non-interactive on that load; later client-side renders still load it via the normal trigger
Transfer cache No duplicate requests, no content flash Serialised into HTML — never for per-user data
ngSkipHydration Unblocks an incompatible component now That subtree loses every hydration benefit

“SSR is enabled and there is a visible flicker on load. Why?” Hydration is not actually running, so the client is destroying the server-rendered DOM and rebuilding it — which is what SSR without hydration does by design, and it costs you LCP and CLS. The usual causes are provideClientHydration() missing from the server bootstrap (it must be in both), or a hydration mismatch failing silently in production. In development the console logs hydration stats and Angular DevTools shows per-component hydration status with an overlay, which localises it quickly.

“A component works client-side and throws a DOM mismatch under hydration.” Almost always direct DOM manipulation — document queries, appendChild, innerHTML, or moving nodes — which Angular does not know about, so the structure it finds is not the structure it expects. The other frequent cause is invalid HTML that the browser silently repairs: a <table> without <tbody> is the classic, since browsers insert one and the repaired DOM no longer matches. Refactor to Angular constructs; ngSkipHydration on the component host is the last resort, and it forfeits hydration for that whole subtree.

“Explain incremental hydration and what it makes newly possible.” It leaves sections of the page dehydrated and hydrates them on a trigger, using @defer with hydrate on .... The server loads those dependencies and renders the real template; the client keeps them deferred until the trigger fires, replaying any events the user produced meanwhile. It is on by default with provideClientHydration() and it enables event replay automatically. The genuinely new capability is @defer above the fold — previously that meant rendering a placeholder and swapping it, causing a layout shift, whereas now the server renders the real content and only interactivity is deferred. hydrate never takes it furthest: on the initial load the block stays static HTML and its JavaScript is never fetched — though a later client-side render of the same block falls back to its regular @defer trigger.

“What can go wrong with the transfer cache?” Caching a per-user response. The cached values are serialised into the page’s HTML, so if a response specific to one user gets cached and that HTML is cacheable by a CDN, you have leaked their data to everyone who gets the cached page. Angular’s defaults are conservative for exactly this reason — only GET/HEAD without Authorization, Cookie or credentials, nothing with no-store/no-cache/private, nothing returning Set-Cookie. The danger is loosening those with withHttpTransferCacheOptions or setting id on a per-user resource without thinking about who else can see the rendered page.

“Two users report seeing each other’s data on a server-rendered page. What do you check first?” Provider scope on the server. Top-level provider values are evaluated once when the server application is parsed, and a useValue keeps that value across every request until the process restarts — so any request-scoped data placed in a useValue is shared between users. The fix is useFactory, which runs per request. The same reasoning applies to module-level mutable state in a service: per-user on the client, per-process on the server. After that I would check the transfer cache and any CDN caching of authenticated HTML.

“The application takes ten seconds to become interactive and logs NG0506.” Something is keeping the application from reporting stability, and hydration will not run until it does. Timers, intervals, unresolved promises, pending microtasks. provideStabilityDebugging() logs the pending tasks — it is on by default in development with provideClientHydration() — and on ZoneJS applications zone.js/plugins/task-tracking additionally gives the stack trace of the macrotask creation. Under zoneless, the fix is usually that some async work needs registering with PendingTasks (or pendingUntilEvent for observables) so Angular knows about it; HttpClient requests and router navigations already register themselves.