Sub topic 12
Measuring the benefits and costs of SSR
This chapter assumes you can build an Angular app with standalone components, have added SSR with ng add @angular/ssr, and know the render modes (Prerender, Server, Client), hydration, the HTTP transfer cache, and @defer blocks from earlier chapters. The goal here is to decide, with numbers, whether SSR is worth its cost for a given route.
Why you need to measure
SSR does not make an app faster by default. It changes when the user first sees content, and it moves work from the browser to your server. A route can get better on one metric and worse on another.
Typical gains:
- Content appears sooner, because the HTML already contains it.
- Crawlers and link previews see real content without running JavaScript.
- Slow devices do less work before the first paint.
Typical costs:
- The server must render on every request (for
RenderMode.Server), which adds time before the first byte. - You run and monitor a Node process, or you rely on a build step for prerendering.
- The browser still downloads and runs the JavaScript for hydration.
- Hydration can add main-thread work that CSR would have spread differently.
You only learn which side wins for your app by measuring.
The metrics that matter
Different metrics capture different parts of the trade-off.
| Metric | What it measures | How SSR usually affects it |
|---|---|---|
| TTFB (Time to First Byte) | Time until the first byte of the response arrives | Worse for `Server` mode, because the server renders before it responds. Best for `Prerender`, which serves a static file. |
| FCP (First Contentful Paint) | When the first text or image appears | Usually better, because HTML contains content. |
| LCP (Largest Contentful Paint) | When the largest visible element appears | Often better, if the element is in the HTML and not waiting on an API call in the browser. |
| INP (Interaction to Next Paint) | Responsiveness to user input | Can get worse right after load if hydration blocks the main thread. Event replay reduces lost input. |
| CLS (Cumulative Layout Shift) | Unexpected layout movement | Can get worse if client-only content appears after hydration and pushes things around. |
| TBT (Total Blocking Time) | Main-thread time blocked by long tasks (lab metric) | Often unchanged or worse, since the same JavaScript still runs. |
TTFB and LCP often move in opposite directions for Server mode. A slow server render delays the first byte, but the HTML that arrives already holds the largest element. Compare the end result, not one number.
A measurement workflow
Measure the same route in three states, under the same conditions: CSR only, SSR with hydration, and (if it applies) prerendered. Use the same network and CPU throttling each time.
- Build a production bundle. Development builds are not representative.
- Run it the way you will deploy it.
- Record lab metrics in Chrome DevTools or Lighthouse with throttling on.
- Repeat each run several times and compare medians, not single runs.
- Compare with field data (real users) once you deploy. Lab results do not capture real devices and networks.
Build and serve the SSR output:
ng build
node dist/my-app/server/server.mjsThe output folder and file names depend on your project name and CLI version. Check the dist folder for the actual path.
To compare against CSR, you can temporarily make every route client-rendered, as in this server routes file:
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '**', renderMode: RenderMode.Client },
];Run the same Lighthouse test, then switch the routes back to Prerender or Server and run it again. Keep everything else identical.
Measuring server cost
The browser metrics only show half the picture. You also pay for server rendering time.
Add timing around the rendering handler in your Node server. A simple Express middleware that logs the duration of each request gives you a baseline:
import express from 'express';
const app = express();
app.use((req, res, next) => {
const start = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - start) / 1_000_000;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms.toFixed(1)}ms`);
});
next();
});
app.get('/health', (req, res) => {
res.send('ok');
});
app.listen(4000, () => console.log('Listening on http://localhost:4000'));In your real server.ts, place the middleware before the Angular request handler so it wraps the render. Watch for these patterns:
- Render time grows with the number of HTTP calls the route makes during rendering. Angular waits for pending work (called stability) before it serializes the HTML. One slow API call delays the whole response.
- Render time under load is higher than render time for a single request. Test with concurrent requests, because Node renders on a single thread by default.
- Memory use grows with request volume if a component or service leaks state between requests.
Do not share state between requests
On the server, a module-level variable is shared by every user. Use Angular services provided in the application injector, which is created per request, and avoid global mutable state.
// Risky: this value is shared between all requests on the server.
let currentUser: string | null = null;
export function setUser(name: string) {
currentUser = name;
}A request that sets currentUser can leak it into the next response. This is a correctness and security problem as well as a performance one.
Measuring hydration cost
After the HTML arrives, the browser downloads the JavaScript, boots Angular, and hydrates. The user sees content but may not be able to interact yet. This gap is the main hidden cost of SSR.
The diagram below shows the timeline for one page load.
To see hydration cost directly:
- Open the Performance panel in Chrome DevTools with CPU throttling at 4x or 6x.
- Record a page load.
- Look for long tasks (marked with red corners) after the first paint.
- Compare them with the same route in CSR mode.
If hydration produces long tasks, the page looks ready but does not respond. Event replay captures clicks and other events during that gap and replays them after hydration, so the input is not lost. It does not make the page respond sooner.
Reducing the costs you find
Use the measurement to choose a fix, and re-measure after each change.
| Symptom | Likely cause | Fix |
|---|---|---|
| High TTFB on a route | Server render waits on slow API calls | Use `Prerender` if the content is static, cache API responses, or fall back to `Client` for that route |
| Duplicate network requests in the browser | Data fetched again after hydration | Make sure the HTTP transfer cache is active (`provideClientHydration`) and that you use `HttpClient`, not a bare `fetch` call |
| Long tasks after first paint | Too much hydration work at once | Use `@defer (hydrate on ...)` for below-the-fold components |
| Layout shift after hydration | Browser-only content that changes size | Reserve space with CSS and avoid swapping content in `afterNextRender` |
| Lost clicks during load | Interaction before hydration | Enable `withEventReplay()` |
| Poor INP right after load | Large hydration cost for heavy components | Defer hydration, or use `ngSkipHydration` only as a last resort |
For example, deferring hydration of a comments section that is below the fold removes its work from the critical path:
@defer (hydrate on viewport) {
<app-comments />
} @placeholder {
<p>Comments</p>
}The server still renders the comments, so crawlers see them, but the browser hydrates them only when they scroll into view.
Deciding per route
A single answer for the whole app is rarely right. Use the measurements to choose per route.
| Route type | Suggested mode | Reason |
|---|---|---|
| Marketing page, docs, blog | `Prerender` | Content is the same for every user, TTFB is the lowest, and no server render is needed at request time. |
| Product page with fresh data and SEO needs | `Server` | Content changes often and must be indexable. Accept the TTFB cost, and cache where you can. |
| Logged-in dashboard | `Client` | No SEO benefit, content depends on the user, and a server render adds cost without a gain. |
Then verify the choice. A route you assumed needed Server may perform well enough as Prerender with a short rebuild cycle. A dashboard you rendered on the server may show no paint improvement because the data call dominates.
Common mistakes
- Comparing a development build with a production build. Development builds are larger and slower.
- Testing only on a fast laptop. Throttle CPU and network to match your users.
- Reading one metric in isolation. A better FCP with a worse INP is not a clear win.
- Measuring a single run. Variation between runs is large, so use medians of several runs.
- Ignoring server cost. A route that is fast for one request can saturate the server under load.
- Enabling SSR for routes behind a login and expecting SEO gains. Crawlers cannot sign in.
Summary
SSR improves what users see first and what crawlers can read. It costs server time, adds hydration work in the browser, and adds operational complexity. Measure TTFB, FCP, LCP, INP, and CLS on production builds under throttling, record server render time under concurrent load, and compare CSR, Server, and Prerender for each route. Use Prerender where content is static, Server where fresh, indexable content is needed, and Client where SSR adds cost with no benefit.
Exercise
A product route uses RenderMode.Server. Lighthouse shows FCP improved from 2.4 s (CSR) to 1.1 s, but TTFB rose from 0.1 s to 0.9 s, and INP in the first few seconds is worse. Name two likely causes and one change for each.
Show answer
The higher TTFB comes from the server waiting on API calls before it can respond. Fixes: cache the API responses on the server, or switch the route to Prerender if the data is static enough. The worse INP comes from hydration blocking the main thread right after load. Fixes: use @defer (hydrate on viewport) or another hydrate trigger for below-the-fold components, and enable withEventReplay() so early clicks are not lost.
Exercise
Why can a module-level variable that stores the current user cause a problem in an SSR app, and what should you use instead?
Show answer
The Node server process handles many requests, and a module-level variable is shared by all of them, so one user's data can appear in another user's response. Use services provided in Angular's dependency injection, which creates a separate injector for each server request.