Sub topic 7
Choosing a render mode for each route
This chapter assumes you can write standalone Angular components, configure routes with the Angular Router, and use ApplicationConfig. It also assumes you have already added SSR to a project with the Angular CLI, so the app has a server config and a provideServerRendering(withRoutes(...)) call. Here you decide, route by route, where and when the HTML for each page is produced.
Why one rendering strategy is not enough
An application usually contains pages with different needs.
- A marketing landing page changes rarely and should load as fast as possible.
- A product page depends on a route parameter and on data that changes often.
- An account dashboard sits behind a login, and search engines never see it.
Server rendering every page per request wastes server time on the landing page. Prerendering everything cannot work for a page that needs per-request data. Client rendering everything gives the dashboard no benefit from the server at all. Angular's @angular/ssr package lets you choose a strategy for each route with a list of ServerRoute objects.
The three render modes
The RenderMode enum has three values you will use.
| Mode | When HTML is produced | Where it runs | Typical use |
|---|---|---|---|
| `RenderMode.Prerender` | At build time | Build machine | Content that is the same for every visitor |
| `RenderMode.Server` | On each request | Your server | Content that depends on the request or on fresh data |
| `RenderMode.Client` | After the JavaScript loads | The browser | Pages behind a login, or pages that rely heavily on browser-only APIs |
With Prerender, the build runs your app once per route and writes the resulting HTML into the output folder. A request for that route is answered with a static file. With Server, the Node server runs the app for every request. With Client, the server sends the plain application shell (index.html without rendered route content) and the browser builds the page.
Defining server routes
Server routes live in their own file, conventionally app.routes.server.ts. The CLI creates it when you add SSR.
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{ path: 'products/:id', renderMode: RenderMode.Server },
{ path: '**', renderMode: RenderMode.Client },
];This list is separate from the router's Routes array. The router config describes components and navigation. The server route list describes only how each URL is rendered on the server. You connect the list to the application in the server config:
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering(withRoutes(serverRoutes))],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);Because this config is merged only into the server bundle, the browser never loads the server route list.
How paths are matched
Server route paths use the same pattern syntax as the router: static segments, :param segments, and the ** wildcard. Angular matches the requested URL against the server routes in the order you list them, and the first match decides the render mode. Put specific paths before general ones. If ** came first in the list above, every URL would be client rendered and the other two entries would never apply.
If you want a default for everything you did not list, end the list with a ** entry. Without one, URLs that match no entry fall back to the default behavior of the SSR setup, which can surprise you. An explicit catch-all makes the behavior visible in code.
flowchart TD
A[Request URL] --> B{First matching server route}
B -->|Prerender| C[Static HTML file built earlier]
B -->|Server| D[Render on this request]
B -->|Client| E[Send app shell only]
C --> F[Browser hydrates]
D --> F
E --> G[Browser renders from scratch]The diagram above is incorrectly fenced for this platform, so here is the same flow in the required form.
Prerendering routes that have parameters
A route like products/:id has an unbounded set of URLs. Prerendering needs to know which concrete URLs to build. You supply them with getPrerenderParams, a function that returns an array of parameter objects.
import { inject } from '@angular/core';
import { RenderMode, ServerRoute } from '@angular/ssr';
import { ProductService } from './product.service';
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{
path: 'products/:id',
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
const products = inject(ProductService);
const ids = await products.listIds();
return ids.map((id) => ({ id }));
},
},
{ path: '**', renderMode: RenderMode.Client },
];Each object's keys must match the route's parameter names. Returning [{ id: '1' }, { id: '2' }] builds /products/1 and /products/2. The function runs in an injection context, so inject() works inside it.
A few details matter here:
getPrerenderParamsruns at build time. Any service it calls must work on the build machine, including its network access and credentials.- The list of IDs is frozen when the build finishes. A product added later has no prerendered file until you rebuild.
- With a catch-all
**entry set toClient, a product that was not prerendered is still served as an app shell, and the browser renders it. If you instead want the server to render unknown IDs per request, the route must useRenderMode.Server.
Choosing between the two for a parameterized route depends on how fast the data changes. A documentation site with a few hundred stable pages suits Prerender. A shop with a changing catalog and live prices suits Server.
Setting defaults and status codes
A ServerRoute accepts more than a path and a mode. Two options are common.
statussets the HTTP status code of the response. You can mark your not-found page withstatus: 404.headersadds response headers to that route, for example cache control.
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '',
renderMode: RenderMode.Prerender,
headers: { 'Cache-Control': 'public, max-age=3600' },
},
{ path: 'products/:id', renderMode: RenderMode.Server },
{ path: 'not-found', renderMode: RenderMode.Server, status: 404 },
{ path: '**', renderMode: RenderMode.Client },
];Setting the status matters for search engines. A page that says "not found" but returns 200 is treated as a real page and can be indexed.
What each mode means for your code
The mode changes what your component code can assume.
Server and Prerender
Your components run in Node. Code that touches window, document, or localStorage directly will throw unless you guard it, as covered in the chapter on platform APIs. For Prerender, the code runs at build time, so there is no request object, no cookies, and no logged-in user. A component that reads a cookie to personalize its output produces the same anonymous HTML for everyone, and the personalized version appears only after hydration, which often causes a visible flash or a mismatch.
For Server, request-specific data is available through the request injected on the server, so personalization is possible. Be careful with caching in front of the server, because a cached personalized page can be served to the wrong user.
Client
Your components run only in the browser, so you can use browser APIs freely. No server-rendered DOM exists to hydrate, so Angular builds the page normally. You lose the early content and the crawler-friendly HTML for that route, which is acceptable for authenticated areas.
A decision checklist
Work through these questions for each route, in order.
- Does the page need to appear in search results or link previews? If not,
Clientis a reasonable choice. - Is the HTML identical for every visitor and known at build time? Choose
Prerender. - Does the HTML depend on the request, on the user, or on data that changes between builds? Choose
Server. - Does the page depend heavily on browser-only APIs, such as a canvas editor or a map library? Choose
Clientand avoid fighting the server.
When two answers compete, pick the one that matches the data's freshness requirement first, and the performance goal second. A fast page with stale prices is a worse result than a slower page with correct ones.
Common errors
- Server routes in the wrong order. A broad pattern placed above a specific one hides the specific one. Order from most specific to least specific.
- Missing
getPrerenderParams. Marking a parameterized route asPrerenderwithout this function fails the build, because Angular cannot know which URLs to generate. - Build-time data access that fails in CI. The prerender step calls your services. If they need an API that the build environment cannot reach, the build fails or produces empty pages.
- Stale prerendered pages. Prerendered output never updates by itself. Schedule a rebuild when the underlying content changes.
- Assuming the server route list replaces the router. It does not. A URL missing from the router still has no component to render, whatever its server route says.
Checking the result
After building, look at the output. Prerendered routes produce an index.html file in a folder named for the route inside the browser output directory. Open one and confirm that the content you expect appears in the HTML source, not only in the rendered page. For Server routes, request the URL with curl and read the response body. For Client routes, the response contains only the app shell, which shows you the route is working as designed.
Exercise
Your app has a /blog/:slug route. The posts are written in Markdown, and the list of slugs is known at build time. Which render mode do you choose, and what extra function must you provide?
Show answer
Choose RenderMode.Prerender. Provide getPrerenderParams on the server route, returning an array of objects such as { slug: 'first-post' }, one for each post. Angular then builds a static HTML file for every slug at build time.
Exercise
A server route list is [{ path: '**', renderMode: RenderMode.Client }, { path: 'products/:id', renderMode: RenderMode.Server }]. Users report that product pages never contain server-rendered content. What is wrong and how do you fix it?
Show answer
The first matching entry wins, and ** matches every URL, so products/:id is never reached. Move the ** entry to the end of the list so the specific route is matched first.
Exercise
A prerendered home page reads a theme cookie in a service and renders a dark or light layout. Visitors with the dark theme see a flash of the light layout. Why does this happen, and which render mode would let the server see the cookie?
Show answer
Prerendering runs at build time with no request, so there is no cookie and every visitor receives the default light HTML. The browser then switches to dark after hydration. RenderMode.Server renders on each request, so the server can read the cookie from the request and produce the matching HTML (taking care that any cache in front of the server varies by that cookie).