Runtimes
Angular SSR on Node, with streaming
Stream an Angular app from Node with node:http, Express or Connect, from the app config to running it in production.
- Packages
@push-based/angular-ssr-stream-core@push-based/angular-ssr-stream-node- Example
apps/example-node
On this page
This is the setup apps/example-node in the repository uses: Angular compiled
by ngp through Vite, the server bundle run by Node with plain node:http, the
browser build served from disk by the same handler, and every other request
rendered as a streamed page. The handler is also Connect and Express
middleware, so the same steps hold for a server built on those.
Before you start#
This setup builds the app with Vite and
@push-based/,
not the Angular CLI. For an app made by ng new --ssr that keeps
@angular/ssr, follow Angular CLI
instead.
ngp needs Node 26 to build, Vite 8.3 or later, TypeScript 6.0, and every
@angular/* package at exactly 22.3.0-rc.0, the release it compiles
against:
npm install @angular/core@22.3.0-rc.0 @angular/common@22.3.0-rc.0 @angular/compiler@22.3.0-rc.0 \
@angular/platform-browser@22.3.0-rc.0 @angular/platform-server@22.3.0-rc.0 \
@angular/router@22.3.0-rc.0 rxjs tslib
npm install -D @angular/compiler-cli@22.3.0-rc.0 @push-based/vite-plugin-ngp vite typescript@~6.0The app is an ES module ("type": "module" in package.json), with
vite/client in its tsconfig.json's types. Vite starts from an
index.html that loads src/main.ts, which bootstraps the root component as
usual:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My app</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<app-root></app-root>
<script type="module" src="/src/main.ts"></script>
</body>
</html>import { bootstrapApplication } from '@angular/platform-browser';
import { App } from './app/app';
import { appConfig } from './app/app.config';
bootstrapApplication(App, appConfig).catch((error) => console.error(error));The steps below call the root component App, in src/app/app.ts, and its
routes routes, in src/app/app.routes.ts.
1. Install#
npm install @push-based/angular-ssr-stream-core@next @push-based/angular-ssr-stream-node@next
npm install -D @types/node2. The browser config#
Add the interceptor and the stream's providers next to Angular's hydration:
import { provideStreamHydration, streamHttpInterceptor } from '@push-based/angular-ssr-stream-core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import type { ApplicationConfig } from '@angular/core';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([streamHttpInterceptor])),
provideRouter(routes),
provideClientHydration(withEventReplay()),
// After provideClientHydration(): it replaces a provider from there.
provideStreamHydration(),
],
};streamHttpInterceptor reports each request to the renderer on the server,
and in the browser holds back a request the server is already making until its
response arrives on the stream. provideStreamHydration() keeps Angular's
hydration data and block registry in step with the chunks.
3. The server config#
import { mergeApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
export const config = mergeApplicationConfig(appConfig, {
providers: [provideServerRendering()],
});4. The server#
import { createServer } from 'node:http';
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { createNodeHandler } from '@push-based/angular-ssr-stream-node';
import { App } from './app/app';
import { config } from './app/app.config.server';
const handler = createNodeHandler({
rootComponent: App,
config,
eventDispatchContract,
allowedHosts: ['localhost', 'my-app.example.com'],
template: new URL('./index.server.html', import.meta.url),
staticDir: new URL('../client/', import.meta.url),
});
// `vite dev` imports this module for its default export, and serves it itself.
export default handler;
if (import.meta.env.PROD) {
const port = Number(process.env['PORT'] ?? 3000);
createServer(handler).listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
});
}The file is built to dist/server/server.js, so both URLs are relative to
that: the template is dist/, and staticDir is the
browser build in dist/client.
allowedHosts must list every hostname the server answers for: Angular's SSR
host guard rejects any other host header, and the page is answered with
403.
eventDispatchContract is for withEventReplay(): it is the script Angular
needs to queue the clicks made before the page hydrates. The handler adds it to
the template unless the template has it already. The index.server.html ngp
writes for a server build has it; the plain built index.html, and the one
Vite serves in vite dev, don't. Leave it out where the template lacks it and
those clicks are lost; the server logs a warning, once, when the page has
listeners to replay.
Behind a proxy that rewrites the host, see
trustProxy. A Host header that
can't be parsed at all is answered with 400, before the check.
staticDir serves the browser build's files: scripts, styles, icons. A
request for anything else, / and /index.html included, is rendered as a
page. Leave staticDir out when something in front already serves the files,
such as express.static, Nginx or a CDN.
With Connect or Express, use the handler as middleware: app.use(handler).
It renders every GET and HEAD that reaches it as a page, so mount the
routes that answer those, such as an API, before it. Other methods are passed
on to next(), and so is an error, for the app's error handler. Default-export
the app rather than the handler then; see
What the server entry default-exports.
The whole Express setup, with express.static(), API routes and
compression, is on Express.
5. Vite#
import { angularStreamNode } from '@push-based/angular-ssr-stream-node/vite';
import { ngp } from '@push-based/vite-plugin-ngp';
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: { entries: ['index.html'] },
plugins: [
angularStreamNode({ entry: 'src/server.ts' }),
ngp({ ssr: { entry: 'src/server.ts' } }),
],
});ngp's ssr option builds the browser app into dist/client and the server
entry into dist/server, next to index.server.html: the built index.html
plus the event dispatch contract.
angularStreamNode() is for vite dev. It sends each page request to the
handler your server entry default-exports, with index.html as the dev server
transforms it, so the page loads Vite's client and your sources, and SSR
streams as it does in production. List it before ngp, or the dev server
refuses to start: ngp's own dev SSR would otherwise answer page requests first,
and call the handler the wrong way. In a build the plugin does nothing.
6. Develop#
vite dev # http://localhost:5173The dev server serves the sources, and every page is rendered by your handler
and streamed. import.meta.env.PROD is false there, so src/server.ts
doesn't start a server of its own.
7. Build and run#
{
"scripts": {
"dev": "vite dev",
"build": "vite build",
"start": "node dist/server/server.js"
}
}vite build # client to dist/client, server to dist/server
node dist/server/server.js # http://localhost:3000, or $PORTdist/server/server.js still imports the packages Vite left out of the
bundle, so run it where the app's node_modules are, or install the
production dependencies next to dist/ in your image. Angular is bundled.
8. Check that it streams#
Before you put anything in front of the server:
Request a page and print when each piece of the response arrives:
curl -sN -o /dev/null --trace-time --trace-ascii - http://localhost:3000/ | grep 'Recv data'07:51:38.138747 <= Recv data, 3557 bytes (0xde5)
07:51:40.145185 <= Recv data, 807 bytes (0x327)The shell comes at once, as one line or a few with the same time. A line that
comes later is a chunk, sent when a @defer block's data was there: here, one
block whose request took two seconds. A page with nothing slow on it arrives
in one piece, so check one that waits for data. If such a page still arrives
all at once, something held the response back until it was complete; see
Checking that a response streams.
9. Behind a proxy#
A proxy, a CDN or compression middleware can hold the response back until it
is complete, and the page then arrives all at once. The handler sends
X-Accel-Buffering: no for Nginx, and calls res.flush() after each chunk for
compression; for the rest, read
Streaming through proxies.
10. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.