Sub topic 3
The server config, server entry, and Node server
This chapter assumes you know standalone components, ApplicationConfig, and basic Node.js and npm. It also assumes you have already run ng add @angular/ssr on a project, as covered in the previous chapter. Here you will look at the three files that command adds, and at how a request travels through them.
The three pieces
SSR needs three things that a browser-only app does not:
- A server config that tells Angular how to render on the server.
- A server entry that bootstraps the application for each render.
- A Node server that receives HTTP requests and returns the rendered HTML.
The server config
The browser config in app.config.ts stays the single source of truth. The server config extends it with mergeApplicationConfig, which concatenates the providers arrays.
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);provideServerRendering registers the server platform services. withRoutes(serverRoutes) attaches the per-route render mode list. Anything you add to appConfig, such as provideRouter or provideHttpClient, is therefore used on both sides. Put a provider in serverConfig only when it must exist on the server alone.
The server routes
Server routes are separate from the router's Routes. They describe how each URL is rendered, not which component it shows.
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{ path: 'products/:id', renderMode: RenderMode.Server },
{ path: '**', renderMode: RenderMode.Client },
];The '**' entry is a catch-all, so keep it last. A later chapter explains how to choose each mode. For now, note that this file is what withRoutes consumes.
The server entry
main.server.ts is the server counterpart of main.ts. It exports a function that bootstraps the app 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;The function is exported but not called here. Angular calls it once for every render, so each request gets a fresh application instance. That isolation stops one user's state from leaking into another user's response. Your root component may be named App in newer projects, so match the name in your own main.ts.
The Node server
server.ts is an Express app. Its job is to serve static files and hand everything else to Angular.
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, () => {
console.log(`Server listening on http://localhost:${port}`);
});
}
export const reqHandler = createNodeRequestHandler(app);Three details matter:
index: falsestops Express from serving a staticindex.htmlfor/. Angular must render that route instead.angularApp.handle(req)resolves to aResponse, ornullwhen no server route matches. Callingnext()onnulllets Express produce its normal 404.reqHandleris exported so the same app can run behind a platform that supplies its own listener, such as a serverless host or the dev server.isMainModuleensuresapp.listenruns only when you start the file directly.
Building and running
ng build
node dist/my-app/server/server.mjsThe build writes two folders. dist/my-app/browser holds the client bundles and any prerendered pages. dist/my-app/server holds the server bundle. Replace my-app with your project name.
Common errors
- Blank page or client-only render: the route fell through to
RenderMode.Client, orindex.htmlwas served statically. Check theindex: falseoption and the order of your server routes. - Provider missing on the server: it was added only to
main.tsinstead ofappConfig, so the server never saw it. - Port already in use: another process holds port 4000. Set
PORTto a different value.
Exercise
Why does main.server.ts export a function instead of calling bootstrapApplication immediately, and what happens if express.static is left without index: false?
Show answer
Angular calls the exported function once per request, which gives every render a fresh application instance and prevents state from leaking between users. Without index: false, Express serves the static index.html for / before Angular sees the request, so that route is not server rendered.