SSR and hydration in Angular
With server-side rendering, the server sends ready HTML, so the product page shows fast and search engines can read it. Hydration then makes that HTML alive in the browser without drawing it again. You must know what can break it (browser-only code, different data on server and client, direct DOM changes), how event replay keeps early clicks, and how incremental hydration and render modes keep the JavaScript small.
Author: bezzad
Contents
The problem: an empty page for Google and for phones
Our shop is a normal Angular app (client-side rendering). The server sends an almost empty index.html and a big JavaScript file. Then:
- On a slow phone, the product page is white for 3 seconds, until the JavaScript is downloaded and has run.
- Link previews in chat apps show no title and no image, because their bots do not run JavaScript.
- Search ranking is weak for product pages.
Server-side rendering (SSR) fixes this. But it brings new kinds of bugs.
How SSR and hydration work
- On the server, Angular runs the app for the URL, waits for the HTTP calls, and sends full HTML.
- In the browser, the user sees the page at once. The JavaScript downloads in the background.
- Hydration: Angular starts, walks the existing DOM and connects it to the components. It reuses the DOM nodes, it does not destroy and draw them again. So there is no flicker.
- Until hydration ends, buttons do not work. Event replay records clicks and key presses in that time and runs them after hydration.
// a new project: ng new shop --ssr (or ng add @angular/ssr)
// app.config.ts
import {
provideClientHydration, withEventReplay, withIncrementalHydration,
} from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
provideClientHydration(withEventReplay(), withIncrementalHydration()),
],
};
No double requests: the HTTP transfer cache
The server already called /api/products/7. Without help, the browser would call it again during hydration. With provideClientHydration, HttpClient puts the server responses into the HTML, and the browser uses them on the first load.
- By default it caches GET and HEAD requests.
- Requests with an Authorization header are not cached by default, so private data does not land in the HTML.
- This only works with HttpClient. A plain fetch call runs twice.
Code that only works in the browser
On the server there is no window, no document, no localStorage and no real screen size. Code that touches them during render fails on the server.
export class PriceTag {
// Bad: crashes on the server, localStorage is not defined.
// currency = localStorage.getItem('currency') ?? 'EUR';
currency = signal('EUR');
constructor() {
afterNextRender(() => {
// Runs only in the browser, after the first render.
const saved = localStorage.getItem('currency');
if (saved) this.currency.set(saved);
});
}
}
- afterNextRender and afterEveryRender run only in the browser. Use them for localStorage, measuring elements, and third-party widgets.
- isPlatformBrowser(inject(PLATFORM_ID)) tells you where the code runs. Use it rarely. Many branches make the server and the browser render different things.
- If the server must know the value (so the first HTML already has the right currency), keep it in a cookie. On the server, read it from the request. Angular 19 and newer have a REQUEST token for this.
Hydration mismatch
Hydration expects the browser to build the same DOM as the server. When it does not, Angular shows an error (NG0500 family) in development, and may draw that part again.
Common causes:
- Different data: Date.now(), Math.random(), the user’s time zone or language used during render.
- Direct DOM changes with innerHTML, document.createElement or a jQuery plugin. Angular does not know about those nodes.
- Invalid HTML, like a div inside a p, or a table without tbody. The browser fixes the HTML, so its DOM differs from what the server meant.
- A CDN or proxy that changes the HTML, for example by removing comments. Angular uses comment nodes and an ngh attribute for hydration.
For a component you cannot fix now, add the ngSkipHydration attribute on its host. Angular then draws it again on the client. This is a way out, not a solution.
Incremental hydration: wake parts only when needed
<app-product-details [product]="product()" />
@defer (hydrate on viewport) {
<app-reviews [productId]="product().id" />
}
@defer (hydrate on interaction) {
<app-size-chart />
}
- The reviews are in the server HTML, so Google and the user see them. But their JavaScript loads only when they come into view.
- hydrate on interaction waits for a click or key press, and event replay runs that first click.
- hydrate never keeps a part as plain HTML forever. Good for a static footer.
- You need withIncrementalHydration() in the providers.
Render modes per route
// app.routes.server.ts
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{ path: 'products/:id', renderMode: RenderMode.Server },
{ path: 'account/**', renderMode: RenderMode.Client },
{ path: '**', renderMode: RenderMode.Server },
];
- Prerender (SSG): HTML is built once at build time. Fastest, but the same for everyone. Good for the home page and help pages.
- Server: HTML is built on each request. Good for product pages with live prices and stock.
- Client: no SSR. Good for private pages behind login, where SEO does not matter.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| localStorage or window in a constructor | The server crashes or the page is empty. | afterNextRender, or a cookie read on the server. |
| Date.now() or random values in a template | Hydration mismatch. | Make the value on the server and send it, or set it after render. |
| Plain fetch instead of HttpClient | Every request runs twice. | HttpClient with the transfer cache. |
| innerHTML or jQuery on the DOM | Mismatch, broken parts. | Templates and Renderer, or ngSkipHydration for now. |
| SSR for private pages | Slower server, no SEO win. | RenderMode.Client for them. |
| Hydrating the whole page at once | Big JavaScript at start. | @defer with hydrate triggers. |
Summary in 6 lines
- SSR sends ready HTML: fast first view, good SEO and link previews.
- Hydration reuses the server DOM. Event replay keeps clicks made before it ends.
- HttpClient’s transfer cache stops double requests. Private requests are not cached.
- Browser-only code goes in afterNextRender. Values the server needs go in cookies.
- Mismatch comes from different data, direct DOM changes and invalid HTML.
- Incremental hydration and render modes keep the start JavaScript small.