Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 74 ยท Quality and Performance

SSR, Hydration and Prerendering

Understand Angular server-side rendering, static prerendering, hydration, event replay and transfer state, and how to write browser-only code safely.

By default, an Angular app is a client-side rendered (CSR) single-page app: the server sends an almost empty HTML page plus JavaScript, and the browser builds everything. That is simple to host, but the user sees a blank page until the JavaScript has downloaded and run, and crawlers or link-preview bots that don't run JavaScript see nothing useful. Server-side rendering (SSR) fixes this by running the same Angular app on a server and sending finished HTML. Prerendering does the same work once, at build time. Hydration is how the browser then takes over that HTML instead of throwing it away.

You should already know how Angular builds a page, what change detection does, and how lazy routes split the code.

The real Angular code and commands are read-only, because the site cannot run the Angular compiler or a Node server for Angular. The runnable examples are stand-ins: a server that renders HTML as a string with a client that hydrates it, and an event-replay demo in plain JavaScript. API names and defaults change between Angular releases, so check the generated project of your version for the exact shape.

Three ways to produce the HTML

Strategy When the HTML is made Good for Cost
Client-side rendering In the browser, after JS loads Apps behind a login, dashboards Blank first paint, poor for SEO
SSR On the server, for every request Personalized or frequently changing public pages A Node server to run; per-request work
Prerendering (SSG) At build time, once per URL Marketing pages, docs, blogs Content is as old as the last build

You can mix them in one app: prerender the home page and docs, server-render a product page, and keep the dashboard client-side. SSR improves when the user sees content, so it helps first paint and metrics like Largest Contentful Paint, and it gives search engines and social crawlers real content. It does not make the page interactive sooner; that waits for JavaScript. It also costs you: a server to run and monitor, code that must work in two environments, and more to debug.

sequenceDiagram
  participant B as Browser
  participant S as Angular server
  B->>S: GET /courses/angular
  S->>S: Run the app, render to HTML
  S-->>B: Full HTML (plus state and JS links)
  Note over B: User sees the page and can read it
  B->>B: Download and run the JavaScript
  Note over B: Hydration reuses the HTML and attaches listeners
  Note over B: Page is now interactive

The HTML arrives first, so the page is readable early; hydration makes it interactive when the JavaScript arrives.

Adding SSR

You may read about Angular Universal in older articles. That was the name of the separate project (@nguniversal/express-engine, ng add @nguniversal/express-engine, npm run build:ssr, npm run serve:ssr) that added server rendering. Since Angular 17 its code lives in the main framework as the @angular/ssr package, and the commands below replace those old scripts. The ideas (render on the server, send HTML, hydrate in the browser) are the same.

New projects can be generated with SSR from the start; an existing one gets it with the schematic:

Terminal
ng new my-app --ssr
# or, in an existing project
ng add @angular/ssr

The generated project gains a server entry (main.server.ts), a server config and a small Node server, and the application builder produces both a browser and a server output. The pieces you meet most often:

TypeScript
// app.config.ts: runs in the browser (and on the server, merged with the server config)
import { ApplicationConfig } from '@angular/core';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideClientHydration(withEventReplay())],
};
TypeScript
// app.config.server.ts: added only on the server
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';

const serverConfig: ApplicationConfig = {
  providers: [provideServerRendering(withRoutes(serverRoutes))],
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

The app.routes.server.ts file chooses a render mode per route pattern:

TypeScript
import { RenderMode, ServerRoute } from '@angular/ssr';

export const serverRoutes: ServerRoute[] = [
  { path: '', renderMode: RenderMode.Prerender },            // built once
  { path: 'courses/:slug', renderMode: RenderMode.Server },  // per request
  { path: 'dashboard', renderMode: RenderMode.Client },      // browser only
  { path: '**', renderMode: RenderMode.Server },
];

A prerendered route with parameters (like courses/:slug) must also list which values to build (through a getPrerenderParams function), because the build cannot guess them. Details of this API have shifted between releases, so follow the generated files and the guide for your version.

Hydration

Without hydration, the browser would receive server HTML, then Angular would start, destroy that DOM and build it again, which makes the page flash and wastes the work. Hydration lets Angular walk the existing DOM, match it against the component tree, reuse each node, and just attach event listeners and state. You enable it with provideClientHydration(), as shown above.

For hydration to work, the HTML Angular builds in the browser has to match what the server produced. Typical causes of a mismatch:

  • Output that depends on the time, a random number or the environment (new Date() in a template).
  • Hand-written DOM changes (innerHTML, document.createElement) outside Angular's control.
  • Invalid HTML that the browser "repairs" (a <div> inside a <p>, a <tr> without a <tbody>), so the parsed DOM differs from Angular's expectations.

Angular reports mismatches in the console in development; fix the cause. For a component that really must manipulate its own DOM, you can put the ngSkipHydration attribute on it to opt that part out, at the cost of rebuilding it in the browser.

Event replay

Between "HTML visible" and "JavaScript ready", a user may already click a button. With event replay, a tiny script in the HTML records those events, and after hydration Angular replays them on the right elements. The user's click is not lost. It is enabled with withEventReplay() in the hydration options, and new SSR projects are generated with it.

Incremental hydration

Hydrating everything at once still means downloading all the JavaScript. Incremental hydration combines hydration with deferrable views: a section is rendered on the server, stays inert HTML, and its code is downloaded and hydrated only when a trigger fires.

TypeScript
provideClientHydration(withIncrementalHydration(), withEventReplay());
HTML
@defer (hydrate on viewport) {
  <app-comments [postId]="post().id" />
} @placeholder {
  <p>Comments are loading</p>
}

The comments are in the server HTML for crawlers and readers, but their JavaScript is fetched when the section scrolls into view. Triggers such as hydrate on interaction, hydrate on idle, hydrate on timer and hydrate never exist; incremental hydration needs a recent Angular version, so check its status in yours.

Transfer state: don't fetch twice

A page that loads data runs HttpClient calls on the server to build the HTML. If the browser repeated every call during hydration, you would pay twice and the page could even flicker with different data. Angular avoids this: with hydration enabled, HttpClient responses to GET and HEAD requests made on the server are serialized into the page and reused by the browser instead of hitting the network. You can tune it with withHttpTransferCacheOptions(...) (for example to include POST requests or filter some URLs).

For data that did not come from HttpClient, the lower-level TransferState lets you store and read a value by key:

TypeScript
import { Injectable, PLATFORM_ID, TransferState, inject, makeStateKey } from '@angular/core';
import { isPlatformServer } from '@angular/common';

const VISITS = makeStateKey<number>('visits');

@Injectable({ providedIn: 'root' })
export class VisitService {
  private readonly state = inject(TransferState);
  private readonly onServer = isPlatformServer(inject(PLATFORM_ID));

  visits(): number {
    if (this.state.hasKey(VISITS)) {
      return this.state.get(VISITS, 0); // browser: reuse the server's value
    }
    const value = computeVisits();
    if (this.onServer) {
      this.state.set(VISITS, value);    // server: leave it in the page
    }
    return value;
  }
}

Code that must only run in the browser

On the server there is no window, no document global, no localStorage and no layout. Code that touches them at load time crashes the render. The fixes, from best to last resort:

  • Prefer Angular abstractions: inject DOCUMENT instead of using the global, use the Renderer2, and use CSS for layout where you can.
  • Put browser-only work in afterNextRender or afterEveryRender (see lifecycle hooks). Those callbacks run only in the browser, after rendering, which is the right moment to measure elements or start a chart library.
  • Check the platform: isPlatformBrowser(inject(PLATFORM_ID)) guards a branch.
  • Render a placeholder on the server, and the real widget after hydration.
TypeScript
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';

@Component({
  selector: 'app-map',
  template: `<div #host class="map">Map loads in the browser</div>`,
})
export class MapComponent {
  private readonly host = viewChild.required<ElementRef<HTMLElement>>('host');

  constructor() {
    afterNextRender(() => {
      // Only runs in the browser, so touching the DOM and window is safe
      this.host().nativeElement.textContent = `Viewport width: ${window.innerWidth}px`;
    });
  }
}

Remember also that on the server, one process serves many users: never keep per-user data in a module-level variable or a providedIn: 'root' service that outlives the request. Angular creates a fresh application (and injector) per request, so services are safe, but a plain global variable is shared by everyone.

A runnable server-versus-client stand-in

This stand-in renders a view to an HTML string like a server would, then lets a "client" hydrate it: it re-derives the view from its own state, compares it with the existing HTML node by node, reuses what matches and reports what doesn't. In the third scenario the server also embeds its state in the page (transfer state) so the client starts from the same inputs.

TypeScript Stand-in: server HTML, hydration and a mismatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Scenario 2 is the classic bug: the server and the browser each ask for "now" and get different answers, so the nodes differ. Scenario 3 shows the cure for state that has to be identical: compute it once on the server and send it along, which is what transfer state does for HttpClient data. For something like a clock, the better fix is to show it only after the browser has rendered (afterNextRender).

A runnable event-replay stand-in

Click Like before pressing Hydrate now. The page is "server-rendered": the button exists but nothing handles it yet. A tiny recorder remembers the clicks; when you hydrate, real handlers are attached and the recorded clicks are replayed, so none are lost.

Stand-in: clicks before hydration are replayed

The button is the same DOM element before and after: hydration did not rebuild it, it only attached behavior. That is what makes hydration cheaper than re-rendering.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What problem does hydration solve?

    Without hydration, Angular would discard the server HTML and render again. Hydration matches the existing DOM to the component tree and attaches listeners and state.
  2. 2. Which strategy fits a documentation site whose pages change only when you deploy?

    Prerendering builds the HTML once per URL during the build, so it can be served as static files with no server work per request.
  3. 3. A template shows new Date() and the console reports a hydration mismatch. Why?

    The two renders happen at different times, so the text differs. Show time-dependent values after the browser has rendered, or transfer one value from server to browser.
  4. 4. Where is it safe to touch window or measure an element in an SSR app?

    There is no window on the server. afterNextRender and afterEveryRender callbacks run only in the browser, after rendering.
  5. 5. What does transfer state do for HttpClient calls?

    With hydration enabled, responses to GET and HEAD requests made during server rendering are embedded in the page and reused by the browser.

Summary

  • SSR renders the app to HTML on the server for each request, prerendering does it once at build time, and client-side rendering does it all in the browser. Mix them per route with render modes.
  • SSR improves first paint, SEO and link previews; it doesn't make the page interactive sooner and adds a server and two-environment code.
  • Hydration reuses the server's DOM (provideClientHydration). Mismatches come from time or random output, manual DOM edits and invalid HTML.
  • Event replay keeps clicks made before hydration; incremental hydration with @defer (hydrate on ...) delays JavaScript for parts of the page.
  • HttpClient GET responses transfer automatically; TransferState handles other data.
  • Keep browser-only code in afterNextRender or behind a platform check, and never keep per-user data in globals.
  • The Angular code is read-only; the renderer and replay demos are stand-ins.

Next: Deferrable Views and Image Optimization