Full answer
Server rendering runs your Angular code in Node for each request. Three practical topics:
- Reading the request. Angular 20 exports
REQUEST,REQUEST_CONTEXTandRESPONSE_INITfrom@angular/core.inject(REQUEST, { optional: true })is a standard webRequeston the server andnullin the browser. Use it to read cookies (theme, language), theAccept-Languageheader, or the URL. The result must be the same on both sides after hydration, or the browser shows a mismatch, so send server-derived values to the browser withTransferStateor read the same cookie there. - Setting the response.
inject(RESPONSE_INIT, { optional: true })is a mutableResponseIniton the server. Setstatus(404 for a missing course, so search engines do not index a soft 404) andheaders(Cache-Control). The router can also redirect with aRedirectCommandreturned from a guard or resolver, which the server turns into a redirect response. - Avoiding duplicate fetching. With
provideClientHydration(withHttpTransferCache())(included by default when you add SSR with the CLI),HttpClientGET responses made on the server are serialised into the page and reused by the browser's first requests with the same URL and parameters, so no second request is sent. For data not fetched throughHttpClient, put it inTransferState: the server callsset(key, value), and the browser callsget(key, default).
Server-only rules:
- Browser APIs (
window,localStorage,document.cookie) do not exist on the server. UseafterNextRender,isPlatformBrowser, or theDOCUMENTtoken. - The server process serves many users. Anything stored in a module-level variable or a root-level singleton is shared between requests. Per-request data must live in services created for the request (the Angular platform makes one application per request), never in module scope. A cached user name in a global would leak between users.
- Do not call your own public API URL from the server if an internal URL is faster. Use
HttpClientwith a relative URL, handled by an interceptor that prefixes the right base per platform. - Use
PendingTasksfor async work, so rendering waits for it.
Test SSR by viewing the page source (the HTML must contain the content), by disabling JavaScript, and by checking the response status with curl -I.
typescript
// file: ssr-helpers.ts
import { isPlatformServer } from '@angular/common';
import { DOCUMENT, PLATFORM_ID, REQUEST, RESPONSE_INIT, TransferState, inject, makeStateKey } from '@angular/core';
import { ResolveFn } from '@angular/router';
export function readCookie(name: string): string | null {
const request = inject(REQUEST, { optional: true });
const header = request ? (request.headers.get('cookie') ?? '') : inject(DOCUMENT).cookie;
const match = header.split('; ').find((c) => c.startsWith(`${name}=`));
return match ? decodeURIComponent(match.slice(name.length + 1)) : null;
}
export function setStatus(status: number, cacheControl?: string): void {
const init = inject(RESPONSE_INIT, { optional: true });
if (!init) {
return; // running in the browser
}
init.status = status;
if (cacheControl) {
const headers = new Headers(init.headers);
headers.set('Cache-Control', cacheControl);
init.headers = headers;
}
}
export interface Course {
id: string;
title: string;
}
const COURSE_KEY = makeStateKey<Course | null>('course');
export const courseResolver: ResolveFn<Course | null> = (route) => {
const state = inject(TransferState);
const id = route.paramMap.get('id') ?? '';
if (state.hasKey(COURSE_KEY)) {
const cached = state.get(COURSE_KEY, null);
state.remove(COURSE_KEY); // use once, then fetch normally on later navigations
return cached;
}
const found: Course | null = id === 'angular' ? { id, title: 'Angular for Beginners' } : null;
if (isPlatformServer(inject(PLATFORM_ID))) {
if (!found) {
setStatus(404, 'no-store');
}
state.set(COURSE_KEY, found);
}
return found;
};Angular 20.3, strict check passes. The server tokens and `TransferState` types are checked by the compiler, but the code was not run in a server here, so no request or response behaviour is claimed beyond the API shapes.
Key points
- `REQUEST` gives the web Request on the server, and `RESPONSE_INIT` sets status and headers.
- The HTTP transfer cache and `TransferState` avoid fetching again in the browser.
- Browser-only APIs need `afterNextRender` or platform checks.
- Never keep per-user data in module scope on the server.
Common mistakes
- Returning a 200 status with a "not found" page.
- Reading `localStorage` during server rendering, which throws.
- Storing user data in a module-level variable, leaking it to other requests.
Follow-ups
- How does the transfer cache decide which responses to reuse?
- What causes a hydration mismatch, and how do you find it?
- How would you set cache headers per route?
Tips
- Mention the one-application-per-request rule. It is a security point.
- Say that 404 pages must return a 404 status.
- Know both transfer mechanisms: the HTTP cache and `TransferState`.
Evaluation rubric
- Uses REQUEST and RESPONSE_INIT correctly.
- Avoids duplicate fetching and understands transfer mechanisms.
- Recognises server-only safety issues.