Sub topic 2
Adding SSR to a project with the Angular CLI
This chapter shows how to add server-side rendering (SSR) to an Angular project with the CLI. It covers what the CLI changes, how to build and run the result, and how to confirm that the server is rendering your pages. The next chapters cover the server configuration in detail and what hydration reuses.
You should already be comfortable with these topics:
- Standalone components and
ApplicationConfig. - Angular Router basics.
HttpClientbasics.- Basic Node.js and npm usage.
Examples follow the current CLI (Angular 19 and later), which uses the application builder. Older projects built with the browser builder need to migrate to the application builder first. File names and the root component name (App or AppComponent) vary slightly between versions.
Two ways to get SSR
You can enable SSR when you create a project, or add it to an existing one.
# New project with SSR enabled
ng new shop --ssr
# Existing project
cd shop
ng add @angular/ssrng new also asks interactively whether to enable SSR and prerendering if you omit the flag. ng add @angular/ssr installs the package and runs a schematic that edits your project. A schematic is a code generator that creates and modifies files for you.
Both routes give the same result. Commit your work before running ng add, so you can review the changes with git diff.
What the schematic changes
The schematic touches configuration, adds new files, and modifies one existing file. Knowing each change helps when something breaks later.
New dependencies
@angular/ssrcontains the server rendering engine and the route configuration types.expressand@types/expressprovide the Node server that the CLI generates by default.
You can replace Express with another server later. The rendering engine does not depend on it.
New files
| File | Purpose |
|---|---|
| `src/main.server.ts` | Server entry point. It bootstraps the app for the server instead of the browser. |
| `src/app/app.config.server.ts` | Server application config. It merges the browser config with server providers. |
| `src/app/app.routes.server.ts` | Per-route render modes (`Prerender`, `Server`, `Client`). |
| `src/server.ts` | The Node and Express server that renders pages on request. |
The server entry is short. It exports a function that bootstraps the same root component with the server config:
import { bootstrapApplication } from '@angular/platform-browser';
import { App } from './app/app';
import { config } from './app/app.config.server';
const bootstrap = () => bootstrapApplication(App, config);
export default bootstrap;The function is exported instead of being called at the top level because the server must bootstrap a fresh application for each request. Sharing one application instance between users would leak state from one request to the next.
Modified files
Three existing files change.
angular.jsongets new build options, shown below.tsconfig.app.jsonnow includessrc/main.server.tsandsrc/server.tsin itsfileslist, so the compiler sees the server code.src/app/app.config.tsgets hydration and, if you useHttpClient, the fetch backend.
Here is the relevant part of angular.json:
{
"projects": {
"shop": {
"architect": {
"build": {
"options": {
"browser": "src/main.ts",
"server": "src/main.server.ts",
"outputMode": "server",
"ssr": {
"entry": "src/server.ts"
}
}
}
}
}
}
}Each option has a distinct role:
browseris the entry for the client bundle.serveris the entry that renders the app.ssr.entryis the file that runs as the HTTP server.outputModeisserverwhen the output includes a running server, andstaticwhen every route is prerendered into plain files. This chapter usesserver. The route-level choices appear in a later chapter.
The shared application config
The schematic edits app.config.ts, which both the browser and the server use:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
provideClientHydration(withEventReplay()),
],
};Two providers were added or changed by the schematic:
provideClientHydration(...)tells the browser to reuse the server-rendered DOM instead of discarding and rebuilding it. Without it, SSR still sends HTML, but the browser throws that HTML away when Angular starts.withEventReplay()records clicks and similar events that happen before hydration finishes, and replays them afterwards. Both features get their own chapters.provideHttpClient(withFetch())switchesHttpClientfromXMLHttpRequestto thefetchAPI. Angular recommends this for SSR, because the Node server hasfetchbuilt in and does not need anXMLHttpRequestpolyfill.
If your project already called provideHttpClient() without withFetch(), check that the schematic did not leave you with two calls. Duplicated providers can hide interceptors you registered. Keep one provideHttpClient call and add all with... features to it.
Request flow in a built app
Once built, the output has two folders: browser for static assets, and server for the server bundle. Each request goes through the Node server.
The server checks for static files first. Requests for JavaScript, CSS, and images never reach the renderer. Only page URLs do.
Build and run
Build the app for production:
ng buildThe output looks like this:
dist/shop/
browser/ client bundles, index.html, assets
server/ server.mjs and the rendered app bundle
prerendered-routes.jsonThe .mjs extension means the server is an ES module. Start it with Node:
node dist/shop/server/server.mjsThe CLI also adds an npm script named serve:ssr:shop that does the same thing:
npm run serve:ssr:shopThe server listens on port 4000 by default. Set the PORT environment variable to change it.
ng serve also renders on the server when SSR is configured, so you can develop with it. The development server rebuilds on file changes, but it is not the same process as the production Node server. Test the production build at least once before you deploy.
Verifying that SSR works
Opening the page in a browser does not prove anything, because a client-only app looks identical after it loads. Check the raw HTML the server sends instead.
curl -s http://localhost:4000/ | head -n 40If SSR works, the response contains your rendered content, such as headings and list items. If you see only <app-root></app-root> with no children, the server did not render.
You can also confirm in the browser:
- Open DevTools and go to the Network tab.
- Reload and select the first document request.
- Open the Response tab. This shows the HTML as the server sent it, before any JavaScript ran.
Hydration also leaves a mark. In a hydrated page, the <app-root> element carries an ngh attribute, and Angular prints a message to the console during development saying hydration is enabled. The ngh attribute holds the serialized data about the server-rendered DOM that the browser needs.
Common errors after adding SSR
Most problems appear the first time the server renders your existing components. The server runs in Node, which has no window, document, or localStorage.
ReferenceError: window is not defined(ordocument,localStorage,navigator). A component or service touches a browser global while rendering on the server. Guard that code or move it intoafterNextRender. A later chapter covers this in detail.NG0401: Missing Platformor bootstrap failures on the server usually meanmain.server.tsandapp.config.server.tsdo not match, for example when the root component was renamed but the import inmain.server.tswas not.- Hydration warnings in the console such as
NG0500toNG0504andNG0506. These point to mismatches between the server and browser DOM. They are not setup errors, but they often appear right after enabling hydration. The hydration constraints chapter explains how to diagnose them. - A page that never finishes loading on the server. The server waits for the application to become stable. A long-running
setTimeout, a pollinginterval, or an HTTP request that never completes keeps the page waiting. Avoid starting timers during server rendering. - Requests to relative URLs fail on the server. In the browser,
/api/productsresolves against the page origin. Angular's serverHttpClientresolves relative URLs against the request's origin, but code that uses rawfetchornew URL(...)with a relative path will fail. UseHttpClientfor requests that must work in both places.
What not to change yet
Resist editing the generated files straight away. The defaults are a sound starting point:
- Leave
app.routes.server.tsalone until you know which routes need which render mode. The default sends every route through the server or prerender path. - Leave the Express handler in
src/server.tsin place. The next chapter explains each part. - Do not remove
provideClientHydration. SSR without hydration works, but it causes a visible flicker as the browser replaces the server's DOM.
Summary of the setup
- Run
ng add @angular/ssror create the project withng new --ssr. - Review the changes in
angular.json,tsconfig.app.json, andapp.config.ts. - Run
ng build, then startserver.mjswith Node. - Check the raw HTML with
curlto confirm that the server rendered the content. - Fix any code that reads browser globals during rendering.
Exercise
After running ng add @angular/ssr, a teammate opens the app, sees the page, and says SSR is working. Which command or DevTools view gives better evidence, and what should the evidence show if SSR is working?
Show answer
Request the raw HTML, for example with curl -s http://localhost:4000/, or open the first document request in the Network tab and read its Response. If SSR works, the HTML already contains the rendered content (headings, lists, text) inside <app-root>. If <app-root> is empty, the server did not render, even though the page looks fine after JavaScript runs in the browser.
Exercise
Which file in the generated setup exports the function that bootstraps the application on the server, and why is it exported as a function instead of running immediately?
Show answer
src/main.server.ts. It exports a function so the server can bootstrap a fresh application instance for every request. A single shared instance would leak state between users.
Exercise
You build the project and see dist/shop/browser and dist/shop/server. What goes in each folder, and which file do you run with Node?
Show answer
browser holds the client bundles, index.html, and static assets, which the server returns directly. server holds the server bundle. Run node dist/shop/server/server.mjs (or npm run serve:ssr:shop).