Runtimes
Angular SSR on Bun, with streaming
Stream an Angular app from Bun.serve(), or from Elysia, from the app config to production.
- Packages
@push-based/angular-ssr-stream-coreand no adapter- Example
apps/example-bun
On this page
Bun's server speaks web Request and Response, so it needs no adapter:
Bun.serve() hands each request to the core's createStreamingHandler() and
sends the streamed Response it gets back as it is. Angular is still compiled
by ngp through Vite, which builds the browser bundle and a server bundle; Bun
only runs the result.
This is the setup of
apps/example-bun, checked
with Bun 1.4.5.
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#
bun add @push-based/angular-ssr-stream-core@next
bun add -d @types/bunThe core is all a Bun server needs. The build still runs on Node.
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 eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { createStreamingHandler } from '@push-based/angular-ssr-stream-core/server';
import { App } from './app/app';
import { config } from './app/app.config.server';
/** The browser build. This file is built to dist/server/server.js, next to it. */
const client = `${import.meta.dir}/../client`;
/** The built `index.html`, read once: every page is rendered into it. */
const template = await Bun.file(`${client}/index.html`).text();
const handle = createStreamingHandler({
rootComponent: App,
config,
eventDispatchContract,
allowedHosts: ['localhost', 'my-app.example.com'],
loadTemplate: async () => new Response(template),
});
/**
* Every built file but the template, each as its own route, so it's served
* before the renderer. Route keys are URL paths, so file names are encoded.
* `/assets/*` catches a hashed file that no longer exists (an old chunk after
* a deploy) with a 404, instead of rendering a page in its place.
*/
const routes: Record<string, Bun.BunFile | Response> = {
'/assets/*': new Response('Not found', { status: 404 }),
};
for await (const path of new Bun.Glob('**/*').scan({ cwd: client, dot: true })) {
if (path !== 'index.html') {
routes[encodeURI(`/${path}`)] = Bun.file(`${client}/${path}`);
}
}
const server = Bun.serve({
port: Number(process.env['PORT'] ?? 3000),
routes,
// Every other request is a page.
fetch: (request) => handle(request),
});
console.log(`Listening on ${server.url}`);dist/client/index.html is the template, not a page. It is read once, at
startup, and every page request is rendered into a copy of it.
The static files go in routes, one route per file found in dist/client at
startup, and Bun matches those before it calls fetch. So /assets/* and
/favicon.ico are served from disk, and anything else, / included, falls
through to the renderer. A path that isn't a built file never reaches the
disk, so there's nothing to guard against .. in it.
A missing file under /assets/, such as an old hashed chunk after a deploy,
gets a 404 rather than a page.
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.
For the types of Bun, add "bun" to types in tsconfig.app.json.
5. Vite#
import { ngp } from '@push-based/vite-plugin-ngp';
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: { entries: ['index.html'] },
// `vite build` builds every environment, not only the client.
builder: {},
environments: {
client: { build: { outDir: 'dist/client' } },
ssr: {
// Every dependency bundled, so dist/ is all a server needs: no node_modules.
resolve: { noExternal: true },
build: { outDir: 'dist/server', rolldownOptions: { input: 'src/server.ts' } },
},
},
plugins: [ngp({ entries: ['src/main.ts', 'src/server.ts'] })],
});The ssr environment builds src/server.ts, and ngp compiles it, and the
components it imports, with its server compiler. ngp's own ssr option stays
off: it expects a render(url, document) function that returns the whole page
as a string, which is the buffered render this server avoids.
resolve.noExternal: true bundles every dependency into the server build, so
dist/ runs on its own, without node_modules.
6. Develop#
vite dev doesn't run src/server.ts: it serves index.html as it is, and
Angular renders the app in the browser, with HMR but without the stream, and
with a console warning (NG0505) that there was nothing to hydrate. To see the
stream, build and run it with Bun, below.
vite build --watch with bun --watch dist/ doesn't work
either: each rebuild empties dist/server, and Bun restarts while the file is
missing and stops with Module not found.
7. Build and run#
vite build # client to dist/client, server to dist/server
NODE_ENV=production bun dist/server/server.js # http://localhost:3000, or $PORTThe build runs on Node; Bun is only needed to run the result. For production,
ship dist/ and run the same command. Without NODE_ENV=production,
Bun.serve() starts in its development mode.
8. 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.
Bun writes each chunk of the ReadableStream body as it is enqueued, with
nothing to configure.
9. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.
Elysia#
Elysia runs on Bun and passes the Request through
the same way: a handler that returns a Response has it sent as it is,
streamed. The template, the config and the build stay the same; only the end
of src/server.ts changes:
import { staticPlugin } from '@elysiajs/static';
import { Elysia } from 'elysia';
// …the template and `handle`, as above.
new Elysia()
.use(staticPlugin({ assets: 'dist/client', prefix: '/', alwaysStatic: true, indexHTML: false }))
.get('/*', ({ request }) => handle(request))
.listen(Number(process.env['PORT'] ?? 3000));alwaysStatic: true gives each built file a route of its own, the way
routes does above. Without it the plugin mounts a wildcard of its own: /
answers 404, and the app's /* route answers every static file with the
page. The plugin turns it on by itself only when NODE_ENV is production,
and turns it off again past staticLimit (1024 files), so set both
explicitly if the build has more files than that. assets is relative to the working directory, so start the
server from the app's folder.
Unlike the Bun.serve() version above, this serves /index.html itself as a
plain file, the bare template, and renders a page for a missing file under
/assets/ instead of answering 404. Checked with Elysia 1.4.32 and
@elysiajs/static 1.4.12.