Sub topic 2
Writing Code That Runs on Both Server and Browser
This chapter assumes you know Angular components, standalone application configuration, dependency injection, routing, and HttpClient. It also assumes basic Node.js usage and how browsers build a DOM.
Avoid Browser-Only APIs During Server Rendering
Server-side rendering (SSR) executes Angular in a server process. That process does not provide browser globals such as window, document, or localStorage. Code that reads them during construction or rendering can fail before the page reaches the browser.
Use Angular’s afterNextRender for work that needs the browser DOM. Angular runs this callback only after the application renders in a browser.
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`;
});
}
}Prefer template bindings and Angular services over direct DOM manipulation. If a browser-only dependency cannot be changed, isolate it behind a platform check or skip hydration for that component as a last resort.
Avoid Duplicate HTTP Requests
During SSR, Angular may fetch data to produce the initial page. Hydration then starts in the browser. Angular’s HTTP transfer cache records eligible server-side GET responses in the rendered page, allowing the browser to reuse them instead of immediately sending the same requests again.
Enable hydration in the shared application configuration:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideClientHydration(),
],
};The cache is intended for safe, repeatable reads. Do not treat it as a replacement for authentication or authorization checks. Review caching options when responses contain user-specific or sensitive data.
Choose a Render Mode Per Route
Angular SSR can select a rendering strategy for each route:
| Mode | When it runs | Typical use |
|---|---|---|
| Prerender | Build time | Public, mostly stable pages |
| Server | Each request | Personalized or frequently changing pages |
| Client | Browser only | Highly interactive or browser-dependent pages |
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{ path: 'products/:id', renderMode: RenderMode.Server },
{ path: '**', renderMode: RenderMode.Client },
];Use prerendering when build-time data is sufficient. Use server rendering when the response depends on the request. Use client rendering when server execution offers little value or the page depends heavily on browser APIs.
Exercise
Why should a component read window.innerWidth inside afterNextRender instead of its constructor?
Show answer
The constructor can run during SSR, where window does not exist. afterNextRender runs only in the browser after rendering.