Runtimes
Angular SSR on AWS Lambda, with streaming
Stream an Angular app from AWS Lambda through a streaming Function URL and CloudFront.
- Packages
@push-based/angular-ssr-stream-core@push-based/angular-ssr-stream-aws-lambda- Example
apps/example-aws-lambda
On this page
This is the setup of apps/example-aws-lambda. Angular is compiled by ngp
through Vite. The server bundle runs as a Node.js Lambda function behind a
Function URL whose invoke mode is RESPONSE_STREAM. CloudFront sits in front,
sending static files to S3 and every navigation to the function. The stack is
described as one AWS SAM
template. SAM was chosen because the whole stack fits in one declarative file,
and nothing in it is an npm dependency of the app, which CDK or SST would add.
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-aws-lambda@next
npm install -D @types/nodeThe adapter needs neither the AWS SDK nor @types/aws-lambda. Deploying takes
the AWS SAM CLI
and the AWS CLI, installed on their own.
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 handler#
import { join } from 'node:path';
import eventDispatchContract from '@angular/core/event-dispatch-contract.min.js?raw';
import { createStreamingLambda } from '@push-based/angular-ssr-stream-aws-lambda';
import { App } from './app/app';
import { config } from './app/app.config.server';
export const handler = createStreamingLambda({
rootComponent: App,
config,
eventDispatchContract,
// The built client sits next to the server bundle in the deployment package.
templatePath: join(import.meta.dirname, '../client/index.html'),
allowedHosts: ['localhost', `*.lambda-url.${process.env['AWS_REGION']}.on.aws`],
});createStreamingLambda() wraps the handler in awslambda..
Each Function URL event becomes a web Request. The response goes out through
awslambda., with the status and headers first and then each
chunk as the renderer flushes it.
templatePath is the built index.html. It ships in the same zip as the
handler, is read on the first request, and is kept for as long as the
execution environment lives.
allowedHosts must list the Function URL's hostname. Behind CloudFront too:
CloudFront sends the Function URL its own hostname as Host, so that is the
host the request is rendered for. Function URLs look like
<url-id>.lambda-url.<region>.on., and Lambda always sets AWS_REGION to
the function's region, so the pattern above matches any Function URL in the
region the function is deployed to, whichever that is.
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.
5. Vite#
import { ngp } from '@push-based/vite-plugin-ngp';
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: { entries: ['index.html'] },
builder: {},
environments: {
client: {
build: { outDir: 'dist/client' },
},
ssr: {
resolve: { noExternal: true },
build: {
outDir: 'dist/server',
copyPublicDir: false,
target: 'node24',
rollupOptions: {
input: { lambda: 'src/lambda.ts' },
output: { entryFileNames: '[name].mjs', chunkFileNames: '[name]-[hash].mjs' },
},
},
},
},
plugins: [ngp({ entries: ['src/main.ts', 'src/lambda.ts'] })],
});vite build builds both environments: the browser app into dist/client, and
the handler into dist/server/lambda.mjs. The handler is one ES module with
every dependency bundled in (noExternal: true), because the deployment
package has no node_modules. The .mjs extension makes Lambda load it as an
ES module without a package.json.
ngp's own ssr option stays off. It builds a render(url, document) entry,
not a Lambda handler. ngp still compiles src/lambda.ts with its server
compiler, since it's listed in entries.
6. The function, CloudFront and S3#
The whole template is
apps/.
These are the parts that decide whether the page streams.
The function and its URL:
RenderFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: dist/
Handler: server/lambda.handler
Runtime: nodejs24.x
Architectures: [arm64]
MemorySize: 1024
Timeout: 30
FunctionUrlConfig:
AuthType: NONE
# BUFFERED, the default, holds the whole response until the handler
# returns: the page arrives in one piece.
InvokeMode: RESPONSE_STREAMCodeUri: dist/ zips the client and the server together, so
server/lambda.mjs finds ../client/index.html. With AuthType: NONE, SAM
adds both permissions a public Function URL needs: lambda:InvokeFunctionUrl,
and lambda:InvokeFunction limited to calls through the URL.
CloudFront's default behavior sends navigations to the Function URL:
DefaultCacheBehavior:
TargetOriginId: render
ViewerProtocolPolicy: redirect-to-https
AllowedMethods: [GET, HEAD, OPTIONS, PUT, PATCH, POST, DELETE]
Compress: false
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Managed-CachingDisabled
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # Managed-AllViewerExceptHostHeaderPages are never cached. AllViewerExceptHostHeader is
AWS's managed policy for Function URL origins:
a Function URL only answers to its own hostname. Compression stays off on this
behavior, so CloudFront has no reason to hold the body back.
Static files are served from S3, through an origin access control. They match
these patterns: Vite's hashed files under assets/*, plus *.ico, *.svg and
*.png for what public/ holds. Change the patterns if your public/ holds
other files. Everything that doesn't match goes to the function, which renders
it as a page.
7. Develop#
vite dev serves the app client-side, without the function: Angular renders it
in the browser and logs NG0505, as there is no hydration data. To see it stream
before a deploy, run the built function through the stand-in in
Check that it streams.
8. Build and deploy#
vite build # client to dist/client, handler to dist/server
sam deploy --guided # the function, its URL, the bucket and CloudFront
aws s3 sync dist/client s3://<AssetsBucketName> --exclude index.htmlsam deploy prints the stack's outputs: SiteUrl (CloudFront), FunctionUrl
and AssetsBucketName. index.html stays out of the bucket: it's the
template, which only the function reads.
9. Check that it streams#
Neither SAM local nor the Runtime Interface Emulator streams a response. The
example has its own stand-in instead,
scripts/,
which follows AWS's runtime client source. It defines the awslambda global
the way the runtime does. The response stream is a chunked POST to a local
Runtime API, and HttpResponseStream. makes the first write send the
JSON metadata prelude and eight null bytes. A Function URL in front reads the
prelude for the status and headers, and forwards the rest as it arrives.
Copy the example's
scripts/ folder,
both files, into the app. They need nothing but Node:
vite build
node scripts/serve.ts # the built function behind a local Function URL, http://localhost:3000/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.
After a deploy, run it against the Function URL first and then the CloudFront
URL (SiteUrl). If the Function URL streams and CloudFront doesn't, the
buffering is in CloudFront.
10. Stream something#
Nothing streams until a template has a @defer block with a hydrate
trigger: read Making something stream.
Which AWS setups stream#
| Setup | Streams |
|---|---|
Function URL, InvokeMode: RESPONSE_STREAM |
Yes. This is what the adapter is for. |
Function URL, InvokeMode: BUFFERED (the default) |
No. |
| CloudFront in front of a streaming Function URL | Expected, not documented by AWS, and not checked here. |
API Gateway REST API, response transfer mode STREAM |
Yes, but the adapter can't serve it (see below). |
API Gateway REST API, response transfer mode BUFFERED |
No. |
| API Gateway HTTP API | No. |
Anything that calls the function with Invoke |
No. Only InvokeWithResponseStream streams. |
API Gateway used to buffer every Lambda response. REST APIs can now stream:
response transfer mode
STREAM, on a Lambda proxy integration, calls the function with
InvokeWithResponseStream. AWS's page is explicit that "Response streaming is
only supported for REST APIs", so HTTP APIs still buffer. A REST API proxy
integration sends the REST event format (payload 1.0), not the Function URL's
payload 2.0, and this adapter only reads the latter.
AWS documents streaming for Function URLs, InvokeWithResponseStream and API
Gateway REST APIs, and nothing else. Treat anything else as buffering, such as
an Application Load Balancer or Lambda@Edge.
Also from AWS's response streaming page:
- "Lambda function URLs do not support response streaming within a VPC environment."
- "The first 6 MB of your function's response payload has uncapped bandwidth. After this initial burst, Lambda streams your response at a maximum rate of 2 MBps." A streamed response can be up to 200 MB.
- Response streaming is available on the Node.js managed runtimes, which define
the
awslambdaglobal the handler needs. - "Streaming responses incur cost and streamed responses are not interrupted or stopped when the invoking client connection is broken." A client that leaves early doesn't stop the function: the render runs to the end, and you pay for all of it. The function isn't told about the disconnect either, so the adapter gives the request no abort signal. Keep the function's timeout close to your slowest page.
Not checked against AWS#
- A deployment: the template,
sam deploy, the S3 upload and the CloudFront distribution have never run. - That CloudFront passes each chunk on as it arrives. AWS doesn't say either way.
- How the real Function URL forwards the body after the prelude. The local stand-in forwards each chunk at once. The real one is documented to stream, but its buffering of small chunks, if any, isn't documented.
- The
nodejs24.xruntime itself. The stand-in's response stream is checked against the runtime client's own code: with that code driving the same handler, the bytes and timings match. - What the client gets when the handler fails before it writes anything. Locally there is no prelude to read a status from, so the stand-in drops the connection. A real Function URL probably answers 502, but AWS doesn't say.