Runtimes
Angular SSR on Fastify, with streaming
Stream an Angular app from a Fastify plugin, next to your routes, with @fastify/static and @fastify/compress.
- Packages
@push-based/angular-ssr-stream-core@push-based/angular-ssr-stream-fastify- Example
apps/example-fastify
On this page
This is the setup apps/example-fastify in the repository uses: Angular
compiled by ngp through Vite, the server bundle run by Node as a Fastify app,
an API route next to the pages, the browser build served by @fastify/static,
and every other GET rendered as a streamed page by the angularStream
plugin. The plugin is built on the Node adapter, and dev mode uses
its Vite plugin.
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 @push-based/angular-ssr-stream-fastify@next
npm install fastify @fastify/static @fastify/compress
npm install -D @types/nodeThe Node adapter is for vite dev, through its Vite plugin.
2. 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 type { IncomingMessage, ServerResponse } from 'node:http';
import { fileURLToPath } from 'node:url';
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import fastifyCompress from '@fastify/compress';
import fastifyStatic from '@fastify/static';
import { angularStream } from '@push-based/angular-ssr-stream-fastify';
import Fastify from 'fastify';
import { App } from './app/app';
import { config } from './app/app.config.server';
const app = Fastify({ logger: true });
// Before the routes it compresses. `flushOnIdle` sends each chunk of a page
// as it comes, instead of the whole page at the end.
app.register(fastifyCompress, { flushOnIdle: true });
// The API, in a plugin so that its routes are added once @fastify/compress has loaded.
app.register(
async (api) => {
api.get('/health', async () => ({ status: 'ok' }));
// Any other URL under /api is a 404, not a page.
api.get('/*', (_request, reply) => reply.callNotFound());
},
{ prefix: '/api' },
);
if (import.meta.env.PROD) {
// The browser build, one route per file; `vite dev` serves these itself.
// Not `wildcard: true`, the default: its `GET /*` would clash with the pages'.
app.register(fastifyStatic, {
root: fileURLToPath(new URL('../client/', import.meta.url)),
wildcard: false,
// `index.html` is the template, not a page: `/` is rendered.
globIgnore: ['**/*.html'],
});
// A hashed file that no longer exists (an old chunk after a deploy) is a 404,
// not a page. Each real file's own route is more specific, so it still wins.
app.get('/assets/*', (_request, reply) => reply.callNotFound());
}
// Every other `GET` and `HEAD` is a page.
app.register(angularStream, {
rootComponent: App,
config,
eventDispatchContract,
allowedHosts: ['localhost', 'my-app.example.com'],
template: new URL('./index.server.html', import.meta.url),
});
/**
* `vite dev` calls this for each page request, with the dev template on `req`
* and `req.url` rewritten to `/index.html`; Fastify routes the URL the browser
* asked for.
*/
export default function handle(
req: IncomingMessage & { originalUrl?: string },
res: ServerResponse,
next: (error?: unknown) => void,
): void {
req.url = req.originalUrl ?? req.url;
app.ready().then(() => app.routing(req, res), next);
}
if (import.meta.env.PROD) {
const port = Number(process.env['PORT'] ?? 3000);
app.listen({ port }).catch((error: unknown) => {
app.log.error(error);
process.exit(1);
});
}The file is built to dist/server/server.js, so both URLs are relative to
that: the template is dist/, and the static root is
the browser build in dist/client.
The plugin registers one route, GET and HEAD on /*. Fastify picks the
most specific route for a URL whatever order they were registered in, so
/api/health and every file of the browser build are answered by their own
routes, and everything else is rendered as a page. /api/* and /assets/*
call reply.callNotFound(), so a mistyped API URL or an old script name after
a deploy gets Fastify's 404 rather than a page. A POST or a PUT to a
path no route has gets the same 404.
@fastify/static needs wildcard: false. With its default, it registers a
GET /* route of its own, and Fastify refuses to start with two. Without the
wildcard it registers a route per file it finds at startup. globIgnore
leaves out index.html, which is the browser build's copy of the template and
would otherwise be served as /index.html and /, unrendered.
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.
@fastify/compress has to be registered before the plugin, and needs
flushOnIdle: true; see 9. Compression.
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', routes: ['/api'] }),
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(), from the Node adapter, is for vite dev. It calls your
server entry's default export with each page request, and with index.html,
as the dev server transforms it, left on the request. routes: ['/api'] sends
it every request under /api as well, whatever its method and Accept
header, before Vite sees it; it matches /api and /api/health, not
/api.json. List it before ngp, or the dev server refuses to start. In a
build it does nothing.
The default export is what makes this work with Fastify. The plugin calls it
as a node:http request listener, (req, res, next), and a Fastify instance
isn't one. handle() in src/server.ts waits for the app to be ready, then
hands the raw request to Fastify's router with app.routing(req, res); the
page route passes that same raw request on to the template loader, which finds
the dev template on it. It restores req.url first: Vite has rewritten it to
/index.html by then, and Fastify would route and log that instead.
import.meta.env.PROD is false in dev, so the module doesn't listen on a
port of its own, and @fastify/static isn't registered: Vite serves the
browser files.
6. Develop#
vite dev # http://localhost:5173The dev server serves the sources, and every page is rendered by your Fastify
app and streamed, compressed by @fastify/compress as in production. The API
under /api is answered by the same app.
Vite answers everything else: the plugin hands the app the requests routes
names, and pages, a GET or HEAD that asks for HTML (Accept: text/html).
An API outside /api needs its own prefix in routes. To check a page with
curl in dev, send the header a browser sends:
curl -sN -H 'Accept: text/html' http://localhost:5173/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, Fastify and its plugins among them, so run it where the app's
node_modules are, or install the production dependencies next to dist/ in
your image. Angular is bundled.
app.listen({ port }) listens on localhost only, which is Fastify's
default. In a container, or anywhere the server must be reached from another
machine, listen on every interface with app..
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. Compression#
@fastify/compress compresses a page in an onSend hook, and by default
holds the compressed output until the page is complete. With
app. alone, the page arrives in one piece when the
last block is done. Run the check with --compressed to see it:
curl -sN --compressed -o /dev/null --trace-time --trace-ascii - http://localhost:3000/ | grep 'Recv data'flushOnIdle: true flushes the compressor whenever the page pauses, which is
after each burst of chunks (chunks written in the same tick go out together),
without resetting the compression state. With it, the same request streams,
for gzip, Brotli, deflate and zstd alike: the shell at once, each chunk when
its data is there.
Register @fastify/compress before the plugin: it hooks into each route as it
is added, and doesn't touch routes added before it has loaded. A route added
with app.get() at the top level is added at once, before any plugin has
loaded, which is why the example's API is a plugin too.
To leave pages out of compression instead, and let a proxy in front compress
them, pass the route option @fastify/compress reads:
app.register(angularStream, {
// ...
route: { compress: false },
});Scripts, styles and API responses are still compressed.
10. Behind a proxy#
A proxy or a CDN can hold the response back until it is complete, and the page
then arrives all at once. The plugin sends X-Accel-Buffering: no for Nginx;
for the rest, read
Streaming through proxies.
If you set Fastify's handlerTimeout, it limits the whole streamed response,
not just the time to the shell: when it runs out mid-page, Fastify cuts the
connection. Give the page route a longer one with
route: { handlerTimeout: 30_000 }.
11. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.