Sub topic 5
Writing code that runs on both server and browser
This chapter covers how to write Angular code that runs during server rendering and in the browser. It assumes you know components, dependency injection, standalone application config, and HttpClient basics. It also assumes you have already added SSR with the CLI and enabled hydration, as covered in earlier chapters.
Why server code differs from browser code
During SSR, Angular runs your application inside Node.js. Node has no window, no real document, no localStorage, and no layout engine. Angular supplies a server-side DOM implementation so that templates can render, but it is a minimal one. It does not measure pixels or run browser APIs.
Code that touches browser globals directly fails on the server. The usual error looks like this:
ReferenceError: window is not definedTwo kinds of code need care:
- Code that runs while the component is created or the template is rendered. This runs on both server and browser.
- Code that runs later, for example inside an event handler. This runs only in the browser, because the server never receives user events.
So the problem is not "all browser APIs are forbidden". The problem is touching them at a time when the server is also executing your code.
What runs where
Angular renders the application once on the server, waits until the app is stable, serializes the HTML, and sends it. The browser then boots the application again and hydrates it. Constructors, ngOnInit, effects created at startup, and template expressions run in both places.
| Code location | Runs on server | Runs in browser |
|---|---|---|
| Constructor, field initializers | Yes | Yes |
| `ngOnInit`, `ngOnChanges` | Yes | Yes |
| Template expressions | Yes | Yes |
| Event handlers (`(click)`) | No | Yes |
| `afterNextRender`, `afterEveryRender` | No | Yes |
| Timers started in lifecycle hooks | Yes, and they delay stability | Yes |
Option 1: Use render hooks for DOM work
The preferred way to use browser-only APIs is a render hook. afterNextRender runs a callback once, after Angular has rendered the next change into the DOM. afterEveryRender runs after every render. Neither runs on the server.
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.... After hydration, the callback replaces it with the real width. Registering the hook must happen in an injection context, such as a constructor or a field initializer. Calling afterNextRender from a plain method throws an error.
Direct DOM changes inside a render hook are safe for hydration because they happen after Angular has matched the server DOM to the component tree. The same changes made in a constructor are not safe. Hydration constraints are covered in a later chapter.
Phases
Render hooks can be split into phases so that reads and writes do not interleave, which avoids forced layout recalculation. Use the object form:
import { Component, ElementRef, afterNextRender, inject } from '@angular/core';
@Component({
selector: 'app-sticky-note',
template: `<p>Note</p>`,
})
export class StickyNoteComponent {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
afterNextRender({
earlyRead: () => this.el.nativeElement.getBoundingClientRect().height,
write: (height) => {
this.el.nativeElement.style.minHeight = `${height}px`;
},
});
}
}A value returned by one phase is passed to the next. Phases run in the order earlyRead, write, mixedReadWrite, read.
Option 2: Check the platform
Sometimes you need to branch inside normal code, for example in a service. Inject PLATFORM_ID and call isPlatformBrowser or isPlatformServer from @angular/common.
import { Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable({ providedIn: 'root' })
export class ThemeStorage {
private isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
read(): string {
if (!this.isBrowser) {
return 'light';
}
return localStorage.getItem('theme') ?? 'light';
}
}The server returns a fixed default. If the browser then returns something different during the first render, the template can differ between server and browser. That causes a visual flash or a hydration mismatch. Prefer to read the stored value after render, then update a signal:
import { Component, afterNextRender, signal } from '@angular/core';
@Component({
selector: 'app-theme-label',
template: `<span>Theme: {{ theme() }}</span>`,
})
export class ThemeLabelComponent {
theme = signal('light');
constructor() {
afterNextRender(() => {
this.theme.set(localStorage.getItem('theme') ?? 'light');
});
}
}Server and first browser render both produce light, so the DOM matches. The real value appears one render later.
Option 3: Use Angular abstractions
Angular provides injectable wrappers that work on both platforms. Use them before reaching for globals.
DOCUMENTfrom@angular/commonis the document. On the server it is the server-side document. Inject it instead of using the globaldocument.Renderer2creates and changes elements through an abstraction that works on both platforms.ElementRefgives the host element, but itsnativeElementis a server DOM node during SSR.TitleandMetafrom@angular/platform-browserset the page title and meta tags, so crawlers see them in the server HTML.
import { Component, inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
@Component({
selector: 'app-product-page',
template: `<h1>Product</h1>`,
})
export class ProductPageComponent {
constructor() {
inject(Title).setTitle('Product details');
inject(Meta).updateTag({
name: 'description',
content: 'Details for a single product.',
});
}
}This is one of the main reasons to use SSR: the title and description are present in the HTML response.
Third-party libraries
A library that touches window when its module is imported breaks the server even if you never call it. Typical examples are charting, map, and editor libraries. You have three choices:
- Check for an SSR-compatible version of the library.
- Load it lazily inside
afterNextRenderwith a dynamicimport(), so it never loads on the server. - Render the wrapping component only in the browser with
ngSkipHydrationor a client render mode. Those options are covered in later chapters.
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-chart',
template: `<div #canvasHost class="chart"></div>`,
})
export class ChartComponent {
private canvasHost = viewChild.required<ElementRef<HTMLDivElement>>('canvasHost');
constructor() {
afterNextRender(async () => {
const { renderChart } = await import('./chart-lib');
renderChart(this.canvasHost().nativeElement);
});
}
}Here ./chart-lib stands for your own wrapper module around the library. The static import graph never reaches the library on the server.
Timers and application stability
The server waits for the application to become stable before it serializes the HTML. Pending HTTP requests and macrotasks such as setTimeout count as unfinished work. A long timer or an interval started during rendering can delay the response or prevent it from finishing.
Common problems:
- A
setIntervalinngOnInitfor polling. On the server it never lets the app settle. - A long
setTimeoutfor a delayed animation. - An RxJS
intervalortimersubscription created during startup.
Move them into afterNextRender, or guard them with a platform check. Where you only want to avoid the server wait, start them after the browser is ready.
import { Component, DestroyRef, afterNextRender, inject, signal } from '@angular/core';
@Component({
selector: 'app-clock',
template: `<p>{{ now() }}</p>`,
})
export class ClockComponent {
now = signal('');
private destroyRef = inject(DestroyRef);
constructor() {
afterNextRender(() => {
const id = setInterval(() => this.now.set(new Date().toLocaleTimeString()), 1000);
this.destroyRef.onDestroy(() => clearInterval(id));
});
}
}The interval never starts on the server, and the cleanup runs when the component is destroyed in the browser.
Server-only behavior and request data
Some code should run only on the server, for example reading request headers. Angular exposes the incoming request through the REQUEST token from @angular/core, and response details through RESPONSE_INIT. On the browser these tokens are null, so always handle that case.
import { Injectable, inject } from '@angular/core';
import { REQUEST } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class RequestInfo {
private request = inject(REQUEST, { optional: true });
language(): string {
return this.request?.headers.get('accept-language') ?? 'unknown';
}
}Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Reading `window` in a constructor | `window is not defined` during SSR | Move to `afterNextRender` or check the platform |
| Using global `document.querySelector` | Error or empty result on server | Inject `DOCUMENT`, or use `viewChild` |
| `setInterval` in `ngOnInit` | Server response hangs or times out | Start it in `afterNextRender` |
| Different template output depending on `isPlatformBrowser` | Hydration mismatch, flicker | Render the same output first, update after render |
| Importing a browser-only library at the top of a file | Server crash at module load | Dynamic `import()` in `afterNextRender` |
| Calling `afterNextRender` outside an injection context | Runtime error | Register it in a constructor or field initializer |
Choosing between the options
- If you need the DOM after rendering, use
afterNextRender. It is the default choice. - If a service needs a different behavior on each platform, use
PLATFORM_ID, but keep the first rendered output identical. - If Angular has an abstraction for the task (
DOCUMENT,Renderer2,Title,Meta), use it. - If a library cannot run on the server at all, load it lazily in the browser or skip server rendering for that component.
Exercise
A component's constructor calls localStorage.getItem('cart') and prints the count in its template. SSR fails with localStorage is not defined. You fix it with if (isPlatformBrowser(platformId)) in the constructor, and the page now loads, but the browser console warns about a hydration mismatch. Why does the mismatch happen, and how do you fix it without it?
Show answer
On the server the check is false, so the template renders a count of 0. In the browser the constructor reads the real value, so the first render shows a different count than the server HTML, and Angular finds different DOM than it expected. The fix is to start with the same default on both sides, for example a signal set to 0, and then read localStorage inside afterNextRender and update the signal. The server HTML and the first browser render match, and the real count appears right after.
Exercise
A dashboard component starts setInterval(poll, 5000) in ngOnInit. After enabling SSR, requests for the page sometimes time out. What is the cause, and what is the fix?
Show answer
The interval is a pending macrotask that is created during server rendering. The server waits for the application to become stable before sending HTML, and the repeating timer keeps it from settling. Move the setInterval into afterNextRender so it only starts in the browser, and clear it with DestroyRef.onDestroy.