Runtimes
Angular SSR on Netlify, with streaming
Stream an Angular app from a Netlify Function or an Edge Function, from the app config to the deploy.
- Packages
@push-based/angular-ssr-stream-coreand no adapter- Example
apps/example-netlify
On this page
Netlify runs the renderer as a Netlify Function: Vite builds the browser app
into the publish directory and the server into one self-contained function
module, Netlify's CDN serves the files, and every other path reaches the
function, which streams the page. The setup below is the one
apps/example-netlify
uses. There is no Netlify package: the function is
createStreamingHandler() from the core, and the rest is build configuration.
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
npm install -D @types/node @netlify/functions netlify-cli@netlify/functions is only needed for its types.
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 function#
A Netlify Function takes a web Request and a Context and returns a
Response, which is what createStreamingHandler() is. Netlify streams a
Response whose body is a ReadableStream, up to 20 MB and within the
function's 60-second limit
(Functions configuration).
import type { Config, Context } from '@netlify/functions';
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { createStreamingHandler } from '@push-based/angular-ssr-stream-core/server';
import template from 'virtual:template';
import { App } from './app/app';
import { config as appConfig } from './app/app.config.server';
export default createStreamingHandler<Context>({
rootComponent: App,
config: appConfig,
eventDispatchContract,
allowedHosts: ['localhost', '*.netlify.app'],
// The built index.html, bundled into the function by vite.config.ts.
loadTemplate: async () => new Response(template),
});
/**
* Every path, unless a file in the publish directory matches it. A missing
* file under `/assets/` is a 404, not a page.
*/
export const config: Config = {
path: '/*',
excludedPath: ['/assets/*'],
preferStatic: true,
};path: '/*' with preferStatic: true sends every request to the function
unless a file in the publish directory matches it: the files in /assets/ and
/favicon.ico come from the CDN, and every navigation is rendered.
A path with no file behind it is a navigation to the function, so
excludedPath keeps it away from /assets/, where the build's hashed files
are. After a redeploy, a browser still running the previous build asks for
chunks that are gone. It gets Netlify's 404 for them, not a page with
200 text/html that fails as a script. Any other missing file, say
/robots.txt, is still rendered as a page and answers 200: the renderer has
no SSR status codes. Exclude such paths too, or add the files to public/.
allowedHosts must list every hostname the site answers for, your own domain
included: Angular's SSR host guard rejects any other host header, and the
function answers 403. *.netlify.app covers the site's Netlify address and
its deploy previews.
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.
The template is the built index.html, as a string inside the function
(virtual:template, below). Nothing is read from disk or fetched per request,
and the same code runs as an Edge Function. Add its type:
/** The built `index.html`, bundled into the function by vite.config.ts. */
declare module 'virtual:template' {
const html: string;
export default html;
}5. Vite#
Netlify doesn't run Vite, so the build has to hand it a function it can deploy
as it is: one module, with Angular compiled and every dependency bundled in.
The mode picks what is built: vite build builds the Netlify Function, and
vite build --mode edge builds the Edge Function. Each
variant goes to its own folder, so both can be built side by side.
import { readFile, readdir, rm } from 'node:fs/promises';
import path from 'node:path';
import { ngp } from '@push-based/vite-plugin-ngp';
import { type Plugin, type ViteDevServer, defineConfig, isRunnableDevEnvironment } from 'vite';
export default defineConfig(({ command, mode }) => {
const edge = mode === 'edge';
const out = edge ? 'dist/edge' : 'dist/function';
const entry = edge ? 'src/edge-function.ts' : 'src/function.ts';
return {
optimizeDeps: { entries: ['index.html'] },
builder: {},
environments: {
client: { build: { outDir: `${out}/client` } },
ssr: {
// Netlify doesn't install the app's dependencies for the function.
resolve: { noExternal: command === 'build' || undefined },
build: {
outDir: `${out}/netlify/${edge ? 'edge-functions' : 'functions'}/ssr`,
copyPublicDir: false,
rolldownOptions: {
input: { ssr: entry },
output: { entryFileNames: '[name].mjs', chunkFileNames: 'chunks/[name]-[hash].mjs' },
},
},
},
},
plugins: [ngp({ entries: ['src/main.ts', entry] }), netlifyFunction(entry)],
};
});
function netlifyFunction(entry: string): Plugin {
let root = '';
let publicDir = '';
let clientOutDir = '';
let server: ViteDevServer | undefined;
return {
name: 'netlify-function',
configResolved(config) {
root = config.root;
publicDir = config.publicDir;
clientOutDir = path.resolve(root, config.environments['client']?.build.outDir ?? 'dist');
},
resolveId: {
filter: { id: /^virtual:(template|public-paths)$/ },
handler: (id) => `\0${id}`,
},
load: {
filter: { id: /^\0virtual:(template|public-paths)$/ },
async handler(id) {
if (id === '\0virtual:public-paths') {
const files = publicDir
? await readdir(publicDir, { recursive: true, withFileTypes: true })
: [];
const paths = files
.filter((file) => file.isFile())
.map(
(file) =>
`/${path
.relative(publicDir, path.join(file.parentPath, file.name))
.split(path.sep)
.join('/')}`,
);
return `export default ${JSON.stringify(paths.sort())};`;
}
const html = server
? await server.transformIndexHtml(
'/',
await readFile(path.join(root, 'index.html'), 'utf8'),
)
: await readFile(path.join(clientOutDir, 'index.html'), 'utf8');
return `export default ${JSON.stringify(html)};`;
},
},
async writeBundle() {
if (this.environment.name === 'ssr') {
await rm(path.join(clientOutDir, 'index.html'));
}
},
configureServer(devServer) {
server = devServer;
// After Vite's own middlewares, so modules and the files in `public/` are served first.
return () => {
devServer.middlewares.use((req, res, next) => {
if (
(req.method !== 'GET' && req.method !== 'HEAD') ||
!req.headers.accept?.includes('text/html')
) {
return next();
}
void (async () => {
const environment = devServer.environments['ssr'];
if (!environment || !isRunnableDevEnvironment(environment)) {
throw new Error('the ssr environment has no module runner');
}
const { default: handle } = await environment.runner.import<{
default: (request: Request, context: unknown) => Promise<Response>;
}>(entry);
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (typeof value === 'string') {
headers.set(name, value);
}
}
const url = new URL(req.originalUrl ?? req.url ?? '/', `http://${req.headers.host}`);
const response = await handle(new Request(url, { method: req.method, headers }), {});
res.writeHead(response.status, [...response.headers].flat());
if (req.method === 'HEAD' || !response.body) {
await response.body?.cancel();
res.end();
return;
}
// Each chunk is written as soon as the function sends it, and the
// render stops when the browser goes away.
const reader = response.body.getReader();
res.on('close', () => void reader.cancel().catch(() => {}));
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
res.write(chunk.value);
}
res.end();
})().catch((error: unknown) => {
if (error instanceof Error) {
devServer.ssrFixStacktrace(error);
}
next(error);
});
});
};
},
};
}What each part is for:
vite buildbuilds both halves:builder: {}builds the browser app intodist/function/client, then thessrenvironment, whose input is the function. ngp compiles the function with its server compiler; its ownssroption stays off, since that one expects arender(url, document)entry.- One module per function.
noExternalbundles every dependency into the build, and the function lands in its own folder,dist/, with its lazy chunks infunction/ netlify/ functions/ ssr/ ssr. mjs chunks/: Netlify takes every file at the top of the functions directory for a function of its own. Netlify reads theconfigexport from the built file. virtual:templateis the browser build'sindex.html, read once the browser build has written it. Invite devit isindex.htmlas the dev server serves it, with Vite's client in it.virtual:public-pathslists the files inpublic/as URL paths, for the Edge Function'sexcludedPath. The Netlify Function doesn't need it.index.htmlleaves the publish directory.preferStaticserves a file that matches the path, andindex.htmlmatches/: left there, the home page would be the unrendered template. The function has its own copy.vite devstreams. Each page request (GETorHEAD) goes to the function, loaded through thessrenvironment, and each chunk of itsResponseis written as it arrives, so the dev server streams the way the deployed function does. When the browser closes the connection, the body is cancelled and the render stops.
Add the type of the second virtual module next to the first:
/** The files in `public/`, as URL paths (`/favicon.ico`), listed by vite.config.ts. */
declare module 'virtual:public-paths' {
const paths: `/${string}`[];
export default paths;
}6. netlify.toml#
[build]
command = "npm run build"
publish = "dist/function/client"
[build.environment]
NODE_VERSION = "26"
[functions]
directory = "dist/function/netlify/functions"with "build": "vite build" in package.json. netlify.toml names only the
Function's folders, so only the Function is deployed.
NODE_VERSION is the Node.js version the build runs on, which ngp needs to
be 26. Netlify installs any version nvm can, and defaults to Node.js 24
(Manage dependencies).
The function then runs on the build's version if AWS Lambda offers it as a
runtime, and on Node.js 24 otherwise
(Functions configuration).
The bundled function streams the same under Node.js 24.
In a monorepo, the site's base directory is the repository root, where the
workspace installs, and its package directory is the app's folder, where
netlify.toml is. Paths in it are then relative to the base directory
(apps/), and the command builds the app from the
root. The package directory can only be set in the Netlify UI:
Project configuration > Developer settings > Continuous deployment > Build
settings > Package directory. Netlify reads netlify.toml from the package
directory, then the base directory, then the repository root
(Monorepos), so
without it the build never reads the app's netlify.toml.
apps/
is set up that way.
7. Develop#
vite dev # http://localhost:5173The plugin in the Vite config hands each page to the function, so pages stream in dev as they do on Netlify.
8. Build and deploy#
vite build # dist/function: the browser app and the function
netlify serve # http://localhost:8888netlify serve runs the build command, packages the function the way a deploy
does, and serves the result, without an account or a linked site. It is the
closest local check of what Netlify will run. To deploy from the command line:
netlify deploy --buildIn a monorepo, run both at the repository root with --filter <package name>,
which picks the app's package directory.
9. Check that it streams#
With netlify serve running:
Request a page and print when each piece of the response arrives:
curl -sN -o /dev/null --trace-time --trace-ascii - http://localhost:8888/ | 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.
The example streams under netlify serve. It hasn't been timed against a
deployed site yet, so whether anything between Netlify's CDN and the browser
buffers the response is still open: run the same command against your deploy.
10. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.
Edge Functions#
The same handler runs as a Netlify Edge Function, on Deno at the edge. The
example builds it with vite build --mode edge and the same Vite config.
Netlify's bundler accepts it, and under netlify serve it streams and
hydrates like the Netlify Function. The bundle isn't free of Node.js, though:
Rolldown's runtime imports createRequire from node:module, and Angular's
server XHR fallback is a lazy xhr2 chunk that calls require("http"). Both
load only because Deno supports node: modules. The example never loads the
xhr2 chunk, because its HTTP backend answers in-process. Whether it runs
there for an app that makes real HTTP requests hasn't been checked;
provideHttpClient( keeps Angular off it.
import type { Config, Context } from '@netlify/edge-functions';
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { createStreamingHandler } from '@push-based/angular-ssr-stream-core/server';
import publicPaths from 'virtual:public-paths';
import template from 'virtual:template';
import { App } from './app/app';
import { config as appConfig } from './app/app.config.server';
export default createStreamingHandler<Context>({
rootComponent: App,
config: appConfig,
eventDispatchContract,
allowedHosts: ['localhost', '*.netlify.app'],
loadTemplate: async () => new Response(template),
});
/**
* Edge Functions have no `preferStatic`: the build's assets and the files in
* `public/`, listed at build time by vite.config.ts, are left out by path.
*/
export const config: Config = {
path: '/*',
excludedPath: ['/assets/*', ...publicPaths],
};What changes:
No
preferStatic. Edge Functions don't have it (Declarations): every path thatpathmatches reaches the function, files included. So the paths it must not answer are excluded: the build's/assets/*, and each file inpublic/, which the build lists asvirtual:public-paths. A file added topublic/is excluded at the next build. A missing file under/assets/gets Netlify's 404, as with the Function.The build output.
vite build --mode edgewrites the browser app todist/edge/clientand the Edge Function todist/.edge/ netlify/ edge-functions/ ssr/ netlify.tomlnames both and has no[functions]:[build] command = "vite build --mode edge" publish = "dist/edge/client" edge_functions = "dist/edge/netlify/edge-functions" [build.environment] NODE_VERSION = "26"Deploy one or the other, never both: an Edge Function on
/*runs first and answers every page, so the Netlify Function would never be called.50 ms of CPU per request, Netlify's limit for Edge Functions, which counts the time spent running code but not time spent waiting (Limits). Measured in Deno 2.9 on an Apple M-series laptop, the example's bundle took about 13 ms to load and 22 ms for its first render, then about 4 ms per render. A real page renders more, on slower machines, and a cold start pays for loading Angular too. Netlify Functions have no such limit, which makes them the safer default; choose the edge when the page renders well within it.
@netlify/edge-functions is only needed for its types:
npm install -D @netlify/.