Runtimes
Angular SSR on NestJS, with streaming
Stream an Angular app from a NestJS app on platform-express or platform-fastify, next to its controllers, from the app config to running it in production.
- Packages
@push-based/angular-ssr-stream-core@push-based/angular-ssr-stream-nestjs
On this page
This is the setup apps/example-nestjs in the repository uses: Angular
compiled by ngp through Vite, and a Nest app on @nestjs/platform-express
built into the same server bundle. Its controllers answer under /api, and
AngularStreamModule renders every other GET as a streamed page. It is built
on the Node adapter, so most of what that page says holds here too.
On @nestjs/platform-fastify, only the server entry, compression and static
files change; Fastify has those, and apps/
is that setup.
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-nestjs@next \
@nestjs/common @nestjs/core @nestjs/platform-express reflect-metadata
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 Nest module#
Import AngularStreamModule into your root module, next to your controllers:
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { Module } from '@nestjs/common';
import { AngularStreamModule } from '@push-based/angular-ssr-stream-nestjs';
import { HelloController } from './api/hello.controller';
import { HelloService } from './api/hello.service';
import { App } from './app/app';
import { config } from './app/app.config.server';
@Module({
imports: [
AngularStreamModule.forRoot({
rootComponent: App,
config,
eventDispatchContract,
allowedHosts: ['localhost', 'my-app.example.com'],
// Relative to the built server, dist/server/server.js.
template: new URL('./index.server.html', import.meta.url),
staticDir: new URL('../client/', import.meta.url),
}),
],
controllers: [HelloController],
providers: [HelloService],
})
export class AppModule {}The options are the Node adapter's, unchanged; see
createNodeHandler(). The file is
bundled into 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 server answers 403. A
Host header that is more than a host and a port is a 400; see
What Nest sees of a page.
eventDispatchContract is as on Node.
The controller is an ordinary Nest controller:
import { Controller, Get } from '@nestjs/common';
import { HelloService } from './hello.service';
@Controller('hello')
export class HelloController {
constructor(private readonly hello: HelloService) {}
@Get()
get(): { message: string } {
return this.hello.hello();
}
}When the options come from somewhere else, such as ConfigService, use
AngularStreamModule.; see
the reference.
5. The server entry#
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { createRequestListener } from '@push-based/angular-ssr-stream-nestjs';
import { AppModule } from './app.module';
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
// `vite dev` imports this module for its default export, and serves it itself.
export default createRequestListener(app);
// In `vite dev`, an edit to the server runs this module again, which creates a
// new app: close the old one, so its `onModuleDestroy` hooks run.
import.meta.hot?.accept();
import.meta.hot?.dispose(() => app.close());
if (import.meta.env.PROD) {
const port = Number(process.env['PORT'] ?? 3000);
await app.listen(port);
console.log(`Listening on http://localhost:${port}`);
}With the global prefix, /api/hello is the controller, an unknown /api/...
gets Nest's 404 JSON, and every other GET and HEAD renders the Angular
app. Without a prefix, a controller still answers first and anything no
controller takes is rendered.
createRequestListener() turns the app into a node:http request listener for
vite dev. In production, app.listen() starts the server as usual.
6. TypeScript#
Nest reads constructor types from decorator metadata, so the tsconfig the app is built with needs both decorator flags:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}ngp compiles the Angular parts of each file and hands the rest on as
TypeScript. Vite's own transform then compiles the Nest decorators, and it
reads both flags from the tsconfig. Without emitDecoratorMetadata, Nest
warns at startup that HelloController "has no decorator metadata", passes
undefined for HelloService, and /api/hello answers 500.
AngularStreamModule itself is published without decorators, so it works
however your app compiles them.
7. Vite#
import { angularStreamNest } from '@push-based/angular-ssr-stream-nestjs/vite';
import { ngp } from '@push-based/vite-plugin-ngp';
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: { entries: ['index.html'] },
plugins: [
angularStreamNest({ 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. Nest stays out of the
bundle, so Node loads it from node_modules.
angularStreamNest() is for vite dev. It sends each page to the listener
your server entry default-exports, with index.html as the dev server
transforms it, and sends it every other request Vite has no file or module for,
so /api/hello reaches Nest in dev too. List it before ngp. In a build it does
nothing.
8. Develop#
vite dev # http://localhost:5173Pages stream as they do in production, the API answers, and an edit to a
controller or service is live on the next request. import.meta.env.PROD is
false there, so src/server.ts doesn't call listen().
9. 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 imports Nest, reflect-metadata and the other 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.
10. Check that it streams#
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.
11. Static files#
staticDir serves the browser build from the render route: a file in
dist/client is sent from disk, anything else is rendered. A path that
ends in .html, in any case, is left to the renderer, so /index.html and
/INDEX.HTML render too. A missing file under /assets/, such as a chunk
from before a deploy, is a 404 rather than a page. Keep staticDir unless something else serves the files.
If you'd rather use Express's static middleware, leave staticDir out and
register it in src/server.ts, before listen():
app.useStaticAssets(fileURLToPath(new URL('../client/', import.meta.url)), { index: false });index: false matters: without it, / gets the unrendered index.html from
the browser build. /index.html itself is still served from disk as it is, the
bare template, where every other setup on these pages renders it. staticDir
doesn't have that gap.
ServeStaticModule from @nestjs/serve-static answers every GET it can't
find a file for with its own index.html, which leaves nothing for the Angular
app to render. To use it for the browser build, turn that off:
imports: [
ServeStaticModule.forRoot({
rootPath: fileURLToPath(new URL('../client/', import.meta.url)),
serveStaticOptions: { index: false },
exclude: ['/{*any}'], // no index.html fallback
}),
AngularStreamModule.forRoot({ /* no staticDir */ }),
],The order of the imports doesn't matter. AngularStreamModule adds its render
route last, right before Nest's 404 handler, so ServeStaticModule's files,
GraphQLModule's endpoint and anything else a module adds when the app
initializes are answered first.
This is Express only. On Fastify, ServeStaticModule always adds a GET *
route, whatever exclude says, and Fastify refuses to start with two
catch-all routes (FST_ERR_DUPLICATED_ROUTE). Use staticDir or
@fastify/static there; see Fastify.
12. What Nest sees of a page#
Pages aren't controller routes. The render route is added after everything else, so Nest's guards, interceptors and pipes never run for a page, and neither does anything that could buffer or rewrite it. That has two consequences to plan for:
- A global guard doesn't protect pages. An auth guard registered as
APP_GUARDcovers your controllers only; every page stays public. MiddlewareConsumermiddleware doesn't reach pages. With a global prefix,consumer.is scoped toapply(...). forRoutes('*') /api.
Middleware added with app.use() runs for every request, pages included. Put
anything that has to cover pages there: authentication, sessions,
compression.
Errors go to Nest's exception filters only while nothing has been sent: a
Host header that is more than a host and a port is a BadRequestException
(400). A render that fails before its first byte is retried as a buffered
render, and only if that fails too does the error reach the filters, as a
500. Once the shell has gone out, an error is the renderer's: it logs it and
cuts the connection, so the browser keeps what it has and no filter writes a
JSON body into the page.
13. Behind a proxy#
A proxy, a CDN or compression middleware can hold the response back until it
is complete. Pages carry X-Accel-Buffering: no for Nginx, and compression
added with app.use(compression()) is flushed after each chunk; for the rest,
read Streaming through proxies.
Behind a proxy that rewrites the host, set
trustProxy.
14. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.
Fastify#
The same module renders pages on @nestjs/platform-fastify, with the same
options and the same results: the API keeps /api, an unknown /api/...
gets Nest's 404, a missing file under /assets/ is a 404, and a bad
Host is a 400. Every step but static files stays the same.
Install the Nest adapter, the stream's Fastify adapter, which the module loads
only on Fastify, and @fastify/compress if you compress in Node:
npm install @nestjs/platform-fastify @push-based/angular-ssr-stream-fastify@next @fastify/compressThe server entry#
import 'reflect-metadata';
import fastifyCompress from '@fastify/compress';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
import { createRequestListener } from '@push-based/angular-ssr-stream-nestjs';
import { AppModule } from './app.module';
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
app.setGlobalPrefix('api');
// Before the app initializes, so it applies to the controllers and the pages.
await app.register(fastifyCompress, { flushOnIdle: true });
// `vite dev` imports this module for its default export, and serves it itself.
export default createRequestListener(app);
import.meta.hot?.accept();
import.meta.hot?.dispose(() => app.close());
if (import.meta.env.PROD) {
const port = Number(process.env['PORT'] ?? 3000);
await app.listen(port);
console.log(`Listening on http://localhost:${port}`);
}createRequestListener() tells the two platforms apart. On Fastify, the first
request in vite dev initializes the app, starts the Fastify instance
(ready()), and from then on hands each request to Fastify's router.
On Fastify, AngularStreamModule adds a route, GET and HEAD on /*,
rather than middleware. Fastify answers a URL with its most specific route,
so a controller, or a route another module adds, answers first, whichever
order they were added in. The page route is built on the Fastify adapter's
createFastifyHandler(): the
page goes out through reply.send(), so onSend hooks still see it.
Compression#
Register @fastify/compress with flushOnIdle: true, before app.listen().
Without flushOnIdle, the compressed page arrives in one piece once the
render is done. Check it with curl --compressed:
curl -sN --compressed -o /dev/null --trace-time --trace-ascii - http://localhost:3000/ | grep 'Recv data'21:15:36.928001 <= Recv data, 1516 bytes (0x5ec)
21:15:38.932440 <= Recv data, 393 bytes (0x189)To leave pages uncompressed, and compress in a proxy in front, leave
@fastify/compress out. See
@fastify/compress for the details.
Static files#
staticDir works as on Express. A file from it is written straight to the
socket (reply.hijack()), so @fastify/compress doesn't compress it, and
headers that Fastify hooks set with reply.header() aren't sent with it.
Headers that app.use() middleware sets are.
To compress the browser build too, leave staticDir out, install
@fastify/static (npm install @fastify/), and register it in
src/server.ts:
import { fileURLToPath } from 'node:url';
import fastifyStatic from '@fastify/static';
await app.register(fastifyStatic, {
root: fileURLToPath(new URL('../client/', import.meta.url)),
wildcard: false,
globIgnore: ['**/*.html'],
});wildcard: false: by default,@fastify/staticadds aGET /*route of its own, and the app fails to start withFST_ERR_DUPLICATED_ROUTE.globIgnore: ['**/*.html']: without it,/and/index.htmlanswer with the browser build's unrenderedindex.html.
app.useStaticAssets() registers the same plugin, but Nest's type for its
options has no globIgnore. Either way, a missing file under /assets/ is
still a 404.
What Fastify sees of a page#
As on Express, guards, interceptors and pipes don't run for pages. Middleware
added with app.use() and Fastify's own onRequest hooks do, so put anything
that has to cover pages there.