Runtimes
Angular SSR on Deno, with streaming
Stream an Angular app from Deno with Deno.serve, deploy it to Deno Deploy, and what Supabase Edge Functions allow.
- Packages
@push-based/angular-ssr-stream-coreand no adapter- Example
apps/example-deno
On this page
Deno speaks web Request and Response natively, so it needs no adapter
package: createStreamingHandler() from the core is the whole server. Vite with
ngp builds the browser app and one server bundle, and Deno runs that bundle with
Deno.serve(). The template is read with Deno.readTextFile(), and static
files are served by serveDir from @std/http.
The repository's apps/example-deno is this setup, and every block below is
taken from it; its server is
src/server.ts.
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
npx jsr add @std/http@std/http comes from JSR. pnpm (10.9 and later) and Yarn take a jsr:
version directly instead: pnpm add @std/.
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 { createStreamingHandler } from '@push-based/angular-ssr-stream-core/server';
import { serveDir } from '@std/http/file-server';
import { App } from './app/app';
import { config } from './app/app.config.server';
// The bundle is dist/server/server.js: the template sits next to it, the browser build beside it.
const template = await Deno.readTextFile(`${import.meta.dirname}/index.server.html`);
const clientDir = `${import.meta.dirname}/../client`;
const render = createStreamingHandler({
rootComponent: App,
config,
allowedHosts: ['localhost'],
loadTemplate: async () => new Response(template),
});
/**
* Static files from the browser build; every other request is a page, rendered as a stream.
* `/index.html` is the template, so it's rendered too, never served as a file. A missing
* file under `/assets/` (an old hashed chunk after a deploy) stays a 404.
*/
Deno.serve(async (request) => {
const { pathname } = new URL(request.url);
if (pathname !== '/index.html') {
const file = await serveDir(request, { fsRoot: clientDir, showIndex: false, quiet: true });
if (file.status !== 404 || pathname.startsWith('/assets/')) {
return file;
}
}
return render(request);
});serveDir answers every request for a file in dist/client. Anything it
doesn't find is a page, and goes to the handler. showIndex: false and the
/index.html check matter: without them, / and /index.html would be
answered with dist/client/index.html, the template with nothing rendered
into it. A missing file under /assets/ keeps its 404, so a browser asking
for an old chunk after a deploy gets an error, not a page.
The template is index.server.html, which ngp writes next to the server
bundle: the built index.html with the event dispatch contract already in it,
so the handler needs no eventDispatchContract. It is read once, at startup,
and every request gets a fresh Response of it.
allowedHosts must list every hostname the server answers for: Angular's SSR
host guard rejects any other host header, and the server answers 403.
Deno.serve() listens on port 8000, Deno's default. To take the port from the
environment, pass { port: Number( as its first
argument, and run Deno with --allow-env.
Paths in the server are relative to import.meta.dirname, the bundle's
folder, not to the working directory. Deno's --allow-read path is resolved
against the working directory, though, so it has to point at dist from
wherever the server is started.
5. Vite#
import { ngp } from '@push-based/vite-plugin-ngp';
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: { entries: ['index.html'] },
environments: {
ssr: {
// Every dependency bundled: Deno runs it with no node_modules and no import map.
resolve: { noExternal: true },
// The bundle is Deno's main module, so `import.meta.main` would be true in every module in it,
// and `@std/http/file-server` would start its own file server on the working directory.
define: { 'import.meta.main': 'false' },
build: { copyPublicDir: false },
},
},
plugins: [ngp({ ssr: { entry: 'src/server.ts' } })],
});ngp's ssr option builds the browser app into dist/client and
src/server.ts into dist/server/server.js, with a few chunks beside it in
dist/server/assets/. Every dependency is bundled, Angular, @std/http and
the core included, so Deno needs neither node_modules nor a deno.json to
run it; ship the whole dist/server folder.
Types#
vite build runs on Node, and type-checks src/server.ts there, where Deno
doesn't exist. Declare the part of it the server uses:
declare namespace Deno {
function readTextFile(path: string | URL): Promise<string>;
function serve(handler: (request: Request) => Response | Promise<Response>): unknown;
}and add deno.d.ts to include in tsconfig.app.json. Deno itself has the
full declarations (deno types).
6. Build and run#
vite build
deno run --allow-net --allow-read=dist dist/server/server.jsThe server listens on port 8000. It needs to read dist and to listen, and no
other permission.
7. 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:8000/ | 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.
8. Develop#
There is no dev server that renders in Deno: vite dev renders on Node. Rebuild
on every change instead, and let Deno restart on every new build:
vite build --watch
deno run --watch=dist/ --allow-net --allow-read=dist dist/server/server.js--watch=dist/ restarts on the template and the browser build too, not only on
the server bundle's own modules. There is no hot module replacement, and the
build is a production build, so Angular's dev-mode hydration checks are off.
9. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.
Deno Deploy#
Deno Deploy runs the same Deno, with full file system access to the files of
the deployment, so the server above runs there unchanged:
Deno.readTextFile() reads the template and serveDir reads dist/client.
Nothing has to be imported into the bundle. Only two things change:
allowedHostslists the hostname Deploy gives the app, and any custom domain, next tolocalhost.- The deployment has to contain
dist. Build it with Node first: ngp needs Node, and Deploy's builder runs JavaScript with Deno. Then upload the output.
deno deploy uploads the current directory but skips everything
.gitignore lists, and dist usually is. Name it in include, as a
directory, not a glob; a glob such as dist/** does not override
.gitignore:
{
"deploy": {
"org": "my-org",
"app": "my-app",
"include": ["dist"],
"runtime": {
"type": "dynamic",
"entrypoint": "dist/server/server.js",
},
},
}vite build
deno deploy --prodWith include, only dist is uploaded: every dependency is in the bundle,
so the deployment needs no package.json and no install step. org and app
are filled in by deno deploy the first time it runs.
Deno Deploy runs Deno 2.5, which compresses a response when the browser accepts it. That doesn't hold the stream back: each chunk is flushed through the encoder as it's written, and the shell still arrives at once.
Supabase Edge Functions#
Supabase Edge Functions run on Deno too, but they are built for APIs, not pages, and in practice they can't serve this app:
- HTML is rewritten to plain text. On the shared
supabase.codomain, aGETthat returnstext/htmlis served astext/plain. Only a custom domain, a paid add-on, serves HTML. - There is no static hosting. The browser build has to live somewhere else,
such as a public Storage bucket or a CDN, with Vite's
basepointing there. The template can ship with the function throughstatic_filesinsupabase/config.toml, and is read withDeno.readTextFile()as above. - The app lives under a path. A function answers at
/functions/, sov1/<name>/ <base href>and every route sit under that prefix. - Functions ask for a JWT by default. A public page needs
verify_jwt = falsefor the function insupabase/config.toml. - The limits are tight for rendering. Each worker gets 2 s of CPU time, and the bundle has to stay under 20 MB when the CLI bundles it, 5 MB when Supabase does.
Each of these has a workaround, but together they make Supabase a poor host for a server-rendered app. Serve the pages from Deno Deploy or any host that runs Deno, and call your Supabase functions from there. This section has not been checked against Supabase.