Sub topic 5
Writing code that runs on both server and browser
This chapter assumes you can write standalone components and services, use inject(), and have SSR and hydration enabled as in the earlier chapters. Here you learn why some code breaks during server rendering and how to fix it.
Why server rendering breaks browser code
The server renders your application in Node.js. Node has no window, no localStorage, and no real DOM. Code that touches these globals at startup throws a ReferenceError, such as window is not defined, and the server fails to render the page.
The usual causes are:
- Reading
window,document,navigator, orlocalStoragein a constructor, field initializer, orngOnInit. - Third-party libraries that access browser globals when they are imported.
- Measuring element sizes or positions, which have no meaning without a layout engine.
The fix is to run browser-only code only in the browser, or to use an abstraction that works in both places.
Run DOM code with afterNextRender
afterNextRender registers a callback that runs once, after Angular has rendered the component. It runs only in the browser. On the server the callback is skipped.
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-width-box',
template: `<div #host>Measuring...</div>`,
})
export class WidthBoxComponent {
private host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() {
afterNextRender(() => {
this.host().nativeElement.textContent = `Window width: ${window.innerWidth}px`;
});
}
}The server sends "Measuring..." in the HTML. After hydration, the callback replaces it with the real width. Because this change happens after hydration, it does not cause a mismatch.
Call afterNextRender in an injection context, such as a constructor or field initializer. If you need to run on every render rather than once, use afterEveryRender. In older Angular versions, this function was called afterRender.
Check the platform with PLATFORM_ID
Some code is not tied to rendering, such as a service that reads localStorage. For that code, inject the PLATFORM_ID token and test it with isPlatformBrowser.
import { Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable({ providedIn: 'root' })
export class StorageService {
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
get(key: string): string | null {
return this.isBrowser ? localStorage.getItem(key) : null;
}
set(key: string, value: string): void {
if (this.isBrowser) {
localStorage.setItem(key, value);
}
}
}The server returns null for every key. If the stored value changes what the page shows, the server HTML and the browser result can differ. Apply stored values after hydration, for example in afterNextRender, so the first render matches on both sides.
Prefer abstractions over globals
Angular provides injectable replacements for several globals. On the server, they point to a server-side implementation (Domino or a similar DOM emulation) instead of failing.
| Instead of | Use |
|---|---|
| `document` | `inject(DOCUMENT)` |
| `window.location` | `Location` or `ActivatedRoute` from the router |
| Direct DOM changes | `Renderer2` or template bindings |
| `document.title` | The `Title` service |
| `<meta>` tags via the DOM | The `Meta` service |
import { Component, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-page-title',
template: `<h1>Products</h1>`,
})
export class PageTitleComponent {
private readonly document = inject(DOCUMENT);
constructor() {
inject(Title).setTitle('Products');
console.log(this.document.URL);
}
}Title and Meta are worth using because their output is part of the server HTML. Search engines and link previews see the result.
Third-party libraries
A library that reads window when it is imported breaks the server even if you never call it. Two common fixes:
- Load the library inside
afterNextRenderwith a dynamicimport(), so Node never evaluates it. - Place the component that uses it behind
ngSkipHydrationor a client-only route. The next chapters cover both.
Exercise
A service reads localStorage.getItem('theme') in its constructor, and the server build fails with "localStorage is not defined". Name two ways to fix it.
Show answer
Inject PLATFORM_ID and call isPlatformBrowser before touching localStorage, returning a default on the server. Or move the read into afterNextRender so it runs only in the browser after hydration. In both cases, apply the stored theme after hydration so the first render matches the server HTML.