Learn Angular SSR

SSR builds HTML with content on the server (ng new --ssr or ng add @angular/ssr, formerly called Angular Universal), so the menu is readable much sooner (384…

Open Jali's menu page on a phone with a so-so signal, and the first thing you see is a white screen. The menu only shows once the JavaScript has downloaded and run, almost two seconds later.

Server-side rendering (SSR) cuts that wait. The page's HTML, content included, is built on the server before it's sent, so the browser can show the menu right away without waiting for the JavaScript. Once the JavaScript arrives, Angular takes over that HTML instead of redrawing it; that step is called hydration. Picture a menu board already written and hung in front of the cart before the stall opens. Buyers can read it from afar, but they can only order once the cashier arrives. The cashier doesn't rewrite the board; she just stands behind it and starts serving. And if someone rang the bell before she arrived, a good cashier serves them as soon as she's there.

What the server sends: CSR vs SSR

Without SSR (client-side rendering, CSR), the server sends an empty shell. Here's its <body> for /menu:

<body>
  <app-root></app-root>
  <script src="polyfills-5CFQRCPP.js" type="module"></script>
  <script src="main-TWSZUFX7.js" type="module"></script>
</body>

With SSR, the menu is already in the HTML (trimmed, as it came out of the build):

<app-root ng-version="20.3.33" ngh="1" ng-server-context="ssg">
  <h1>Jali's Pancake Stall</h1>
  <app-menu ngh="0">
    <p> Chocolate Cheese Pancake: $8 <button jsaction="click:;">Order</button></p>
    <p> Special Egg Pancake: $10 <button jsaction="click:;">Order</button></p>
    <p class="badge">Items in cart: 0</p>
  </app-menu>
</app-root>

The example app opened in Chrome slowed down like a phone (150 ms latency, 1.6 Mbps, CPU 4x slower):

HTML arrives Menu shows Order button live
CSR 171 ms (empty) 1,760 ms 1,714 ms
SSR 176 ms 384 ms 1,712 ms

Switching SSR on

New project: ng new jalis-pancakes --ssr. Existing project: ng add @angular/ssr. This feature used to be called Angular Universal; since Angular 17 its package is @angular/ssr. The command adds src/server.ts (an Express server), src/main.server.ts, app.config.server.ts and app.routes.server.ts. Here's what ng new --ssr creates in Angular 20.3:

// src/app/app.config.ts: used by the browser, and merged into the server config too
export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes), provideClientHydration(withEventReplay())
  ]
};

// src/app/app.config.server.ts
const serverConfig: ApplicationConfig = {
  providers: [
    provideServerRendering(withRoutes(serverRoutes))
  ]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

// src/app/app.routes.server.ts
export const serverRoutes: ServerRoute[] = [
  { path: '**', renderMode: RenderMode.Prerender }
];

On Angular 22, ng new --ssr writes slightly different code. The block above was made by Angular 20.3. This is what changed, read from the @schematics/angular 22.2 schematic:

So the click measurement in the Hydration section holds for Angular 20.3. On Angular 22, clicks made before hydration are still replayed even when withEventReplay() isn't written.

ng build now makes two bundles and prints Prerendered 2 static routes. at the end. The output is in dist/jalis-pancakes/browser (files for the browser, including menu/index.html) and dist/jalis-pancakes/server, and npm run serve:ssr:jalis-pancakes runs node dist/jalis-pancakes/server/server.mjs on port 4000.

Hydration

In the browser, Angular matches the server's DOM against its template and reuses the nodes already there. In development mode, the console writes Angular hydrated 2 component(s) and 22 node(s), 0 component(s) were skipped.

withEventReplay() records clicks that happen before hydration ends, then replays them. Measured: Order clicked at 430 ms, hydration done at 1,710 ms, and the cart still ended up Items in cart: 1. Without withEventReplay(), the same click is lost and the cart stays at 0.

Hydration needs the browser's DOM to be exactly the same as the server's HTML. A menu written as a <table> holding <tr> rows without a <tbody> breaks it: the browser inserts its own <tbody> while reading the HTML, then the console writes ERROR RuntimeError: NG0501: During hydration Angular expected more sibling nodes to be present., and the Order button no longer grows the cart. Writing the <tbody> yourself in the template fixes it.

window and localStorage don't exist on the server

With SSR, components and services also run in Node.js, and there's no window, document or localStorage there. Say CartStore writes private items = signal<Item[]>(JSON.parse(localStorage.getItem('cart') ?? '[]')). In the browser this works, but ng build prints:

ERROR ReferenceError: localStorage is not defined

/menu gets no prerendered HTML file, and the Node server answers requests for /menu with 404 Not Found. The fix: read localStorage in afterNextRender, which only runs in the browser, after the first render:

@Injectable({ providedIn: 'root' })
export class CartStore {
  private items = signal<Item[]>([])

  constructor() {
    afterNextRender(() => {
      const saved = localStorage.getItem('cart')
      if (saved) {
        this.items.set(JSON.parse(saved))
      }
    })
  }
}

The result: the server HTML says Items in cart: 0, then after hydration the browser reads the two stored items and the badge becomes Items in cart: 2. For other logic, isPlatformBrowser(inject(PLATFORM_ID)) is true in the browser and false on the server. Don't use it to render a different template: Angular doesn't error, but the server's HTML for that part is thrown away and redrawn.

📌 Running the built server

In Angular 20.3, the built server refuses hosts that aren't listed. Run on localhost:8818, the server printed Header "host" with value "localhost:8818" is not allowed. then Falling back to client side rendering., and the page quietly went back to CSR. List the host, for example NG_ALLOWED_HOSTS=localhost node dist/jalis-pancakes/server/server.mjs, or fill security.allowedHosts in angular.json.

⚠️ Server renders that fail, or hydration that misses

TL;DR: SSR builds HTML with content on the server (ng new --ssr or ng add @angular/ssr, formerly called Angular Universal), so the menu is readable much sooner (384 ms vs 1,760 ms in the example) and search engines can read it. Hydration, switched on with provideClientHydration(), makes Angular in the browser reuse the server's DOM instead of redrawing it; withEventReplay() replays clicks that come early. The browser's DOM must match the server HTML (write the <tbody> yourself). The server has no window, document or localStorage: read them in afterNextRender, not while a class is built, or prerendering fails with ReferenceError: localStorage is not defined.

⚡ The server sends HTML with content in it

Write:

ng add @angular/ssr

Meaning: With SSR, the page's HTML, content included, is built on the server, so the menu is readable right away without waiting for the JavaScript. In the example app, the menu shows at 384 ms instead of 1,760 ms, and search engines can read its text. This package used to be called Angular Universal.

⚡ Hydration reuses the server's DOM

Write:

providers: [provideClientHydration(withEventReplay())]

Meaning: Once the JavaScript arrives, Angular in the browser reuses the DOM the server sent instead of redrawing it. withEventReplay() replays clicks that came before hydration ended.

In the exercise, import provideClientHydration from '@angular/platform-browser' and call it inside providers.

⚡ The server has no window or localStorage

Write:

constructor() {
  afterNextRender(() => {
    const saved = localStorage.getItem('cart')
    if (saved) {
      this.items.set(JSON.parse(saved))
    }
  })
}
Guess first: CartStore reads localStorage straight away while the class is built. What happens during ng build?

Prerendering fails with ReferenceError: localStorage is not defined, because that code runs in Node.js too. /menu gets no HTML file, and the server answers 404.

Meaning: window, document and localStorage don't exist on the server. afterNextRender only runs in the browser, after the first render.

What you will learn