← Back to Angular, page 5

angular-0099 · Hard senior

How do you read the incoming request, set the response status and headers, and avoid duplicate data fetching during server-side rendering?

In SSR, inject the REQUEST token to read headers and cookies for the current user, and RESPONSE_INIT to set the status and headers of the rendered page. HttpClient responses are copied to the browser through the HTTP transfer cache, and TransferState moves any other data, so the browser does not fetch it again. Never store per-user data in module-level variables on the server.

Full answer

Server rendering runs your Angular code in Node for each request. Three practical topics:

  1. Reading the request. Angular 20 exports REQUEST, REQUEST_CONTEXT and RESPONSE_INIT from @angular/core. inject(REQUEST, { optional: true }) is a standard web Request on the server and null in the browser. Use it to read cookies (theme, language), the Accept-Language header, 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 with TransferState or read the same cookie there.
  2. Setting the response. inject(RESPONSE_INIT, { optional: true }) is a mutable ResponseInit on the server. Set status (404 for a missing course, so search engines do not index a soft 404) and headers (Cache-Control). The router can also redirect with a RedirectCommand returned from a guard or resolver, which the server turns into a redirect response.
  3. Avoiding duplicate fetching. With provideClientHydration(withHttpTransferCache()) (included by default when you add SSR with the CLI), HttpClient GET 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 through HttpClient, put it in TransferState: the server calls set(key, value), and the browser calls get(key, default).

Server-only rules:

  • Browser APIs (window, localStorage, document.cookie) do not exist on the server. Use afterNextRender, isPlatformBrowser, or the DOCUMENT token.
  • 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 HttpClient with a relative URL, handled by an interceptor that prefixes the right base per platform.
  • Use PendingTasks for 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.