Sub topic 3
The server config, server entry, and Node server
This chapter covers the three pieces that turn an Angular app into a server-rendered one: the server application config, the server entry point, and the Node server that receives HTTP requests. It assumes you know standalone components, ApplicationConfig, dependency injection, and basic Node.js and npm usage. It also assumes you have already added SSR with the Angular CLI, as in the previous chapter.
How the three pieces fit together
When you add SSR, the CLI creates files beside your existing browser bootstrap. Names and locations shift slightly between Angular versions, so check your own project.
| File | Role |
|---|---|
| `src/main.ts` | Bootstraps the app in the browser with `app.config.ts`. |
| `src/app/app.config.server.ts` | Merges the browser config with server-only providers. |
| `src/app/app.routes.server.ts` | Declares a render mode for each route. |
| `src/main.server.ts` | Exports a bootstrap function that renders the app on the server. |
| `server.ts` | Runs an Express server that hands requests to Angular. |
An incoming request moves through them in this order:
The key idea is that server.ts is plain Node code, while the other files are Angular code that also runs in the browser build or in the server bundle. They are built together but run in different places.
The server application config
The browser config in app.config.ts holds providers both environments need: the router, HttpClient, and hydration. The server config adds what only the server needs. Angular does not ask you to repeat the shared providers. It asks you to merge:
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);mergeApplicationConfig concatenates the providers arrays, with the second config's providers placed after the first. Providers later in the list override earlier ones for the same token. This gives you a clean way to replace a browser implementation on the server. For example, you could provide a server-only version of a service that wraps localStorage.
provideServerRendering registers everything Angular needs to produce HTML on the server. That includes a server-side DOM implementation and a platform that replaces browser APIs. The withRoutes(serverRoutes) feature attaches your per-route render mode definitions, which the render-modes chapter covers in detail. For now, treat serverRoutes as a list that says "prerender this path, render that one per request, leave this one to the browser."
What belongs where
Use this rule when deciding where a provider goes:
- If the provider is needed in both environments, put it in
app.config.ts. Examples areprovideRouter,provideHttpClient(withFetch()), andprovideClientHydration. - If the provider only makes sense while rendering on the server, put it in
app.config.server.ts. - If the provider uses browser APIs, either keep it out of the server config or guard it, as the next chapters show.
provideClientHydration stays in the shared config on purpose. The server needs it so it can annotate the HTML it produces, and the browser needs it to read those annotations.
The server entry: main.server.ts
main.server.ts is the file the server build treats as its Angular entry. It exports a function that bootstraps the application with the server config:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';
const bootstrap = () => bootstrapApplication(AppComponent, config);
export default bootstrap;Two details matter here.
First, it exports a function, not the result of calling bootstrapApplication. Angular calls the function once for each render, so each request gets a fresh application instance with its own injector. Nothing leaks between users, as long as your own code keeps request data out of module-level variables.
Second, the function is the default export. The build and the app engine find it by that convention, so do not rename the export.
The root component class may be named App or AppComponent depending on your version. Use the name your project already has.
The Node server: server.ts
The CLI generates an Express server. Its job is small: serve static files, then give everything else to Angular. A typical version looks like this:
import {
AngularNodeAppEngine,
createNodeRequestHandler,
isMainModule,
writeResponseToNodeResponse,
} from '@angular/ssr/node';
import express from 'express';
import { join } from 'node:path';
const browserDistFolder = join(import.meta.dirname, '../browser');
const app = express();
const angularApp = new AngularNodeAppEngine();
app.use(
express.static(browserDistFolder, {
maxAge: '1y',
index: false,
redirect: false,
}),
);
app.use((req, res, next) => {
angularApp
.handle(req)
.then((response) =>
response ? writeResponseToNodeResponse(response, res) : next(),
)
.catch(next);
});
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, (error) => {
if (error) {
throw error;
}
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
export const reqHandler = createNodeRequestHandler(app);Older versions use a slightly different route pattern, such as app.use('/**', ...). The structure is the same.
What each part does
AngularNodeAppEngineis the bridge between Node and Angular. It accepts a Node request, matches the URL against your server routes, renders the app when the route calls for it, and returns a web-standardResponse.express.staticserves the files from thebrowseroutput folder: JavaScript bundles, styles, assets, and prerendered pages. Settingindex: falsestops Express from servingindex.htmlfor/. Angular must handle that request so the route's render mode applies.maxAge: '1y'is safe because the build gives bundles content-hashed file names. A changed file gets a new name, so clients never reuse a stale one.handle(req)returns a promise that resolves to aResponse, or tonullwhen no route matches. In thenullcase the code callsnext(), so Express can return a 404 or run later middleware.writeResponseToNodeResponsecopies the status, headers, and body of the webResponseonto Node'sres. It streams the body, so you do not build the full string in memory.isMainModulechecks whether this file was started directly withnode. Only then does it calllisten. When a platform imports the file instead, the server stays quiet and the platform usesreqHandler.reqHandleris the export that hosting platforms and the dev server use to call your app without opening their own port.
Adding your own routes
Because this is ordinary Express, you can add API endpoints or middleware. Register them before the Angular catch-all handler, or Angular answers first:
app.get('/api/health', (_req, res) => {
res.json({ status: 'ok' });
});
// The Angular handler comes after this.Keep the server file thin. Business logic that renders pages belongs in Angular components and services, where it also works for prerendering. Logic in server.ts only runs for requests that reach Node.
Reading the request inside Angular
Sometimes a component or service needs the incoming request, for example to read a cookie or set a status code. Recent Angular versions provide injection tokens for this: REQUEST, RESPONSE_INIT, and REQUEST_CONTEXT, imported from @angular/core. They hold values only during server rendering, so inject them as optional:
import { Injectable, inject, REQUEST } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LocaleService {
private request = inject(REQUEST, { optional: true });
preferredLanguage(): string {
const header = this.request?.headers.get('accept-language');
return header?.split(',')[0] ?? 'en';
}
}In the browser, request is null, so the service falls back to 'en'. If your Angular version predates these tokens, check its documentation for the equivalent.
Build output and running the server
The CLI configures the build in angular.json. The relevant options sit under the application builder:
{
"server": "src/main.server.ts",
"outputMode": "server",
"ssr": {
"entry": "src/server.ts"
}
}server points at the Angular server entry. ssr.entry points at the Node server file. outputMode can be "server", which produces a deployable Node server, or "static", which only prerenders pages and produces plain files with no server. The exact file location of server.ts depends on your version. The generated angular.json is the source of truth.
After ng build, the output folder has two parts:
dist/<project>/browserholds what the client downloads.dist/<project>/serverholds the server bundle, includingserver.mjs.
Run it with Node:
ng build
node dist/my-app/server/server.mjsThe CLI also adds an npm script named serve:ssr:<project> that runs the same command. During development, ng serve renders on the server too, so you see SSR problems before you build.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Page loads but is not server-rendered | `index.html` served statically, often because `index: false` is missing or a proxy serves the file | Make sure requests reach the Angular handler, and check the response source with `curl`. |
| Server crashes with `window is not defined` or `document is not defined` | Browser global used in a constructor or at module load | Move it into `afterNextRender`, or guard it, as the next chapter shows. |
| `NullInjectorError` for a server-only token in the browser | The provider is in `app.config.server.ts`, but the code runs in both environments | Inject it with `{ optional: true }` or add a browser provider too. |
| Routes return 404 from Angular | `serverRoutes` does not cover the path | Add a matching entry or a `**` fallback. |
| Custom API route never responds | Registered after the Angular catch-all | Register it before the Angular handler. |
| Two users see each other's data | Per-request state kept in a shared singleton | Use per-request providers or the request tokens. |
Beyond Express
AngularNodeAppEngine is the Node flavor of a more general class, AngularAppEngine, which works with web-standard Request and Response objects. Frameworks and runtimes that use those objects, such as edge platforms, can call handle directly. The Express setup is a convenience, not a requirement. What stays the same on any host is the pattern: serve static files first, then give unmatched requests to the engine.
Exercise
Your team adds an /api/orders endpoint to server.ts by calling app.get('/api/orders', ...) at the bottom of the file, after the Angular catch-all handler. Requests to /api/orders return the rendered Angular app instead of JSON. Why does this happen, and how do you fix it? Also, why does main.server.ts export a function rather than an already bootstrapped application?
Show answer
Express runs middleware in registration order. The Angular handler was registered first and answers every request that no static file matches, so the API route is never reached. Move the app.get('/api/orders', ...) registration above the Angular handler. main.server.ts exports a function so Angular can call it for each render and create a fresh application instance and injector per request. This keeps one user's state from leaking into another user's response.