> [Agent navigation index](/llms.txt)

# Deploying to Node and AWS Lambda

Package the generated Brix application on Node or AWS Lambda, or build a custom Lambda event handler.

Choose one path before editing configuration: **Node** for a long-running process, **generated HTTP
Lambda** for the complete routed application, or **custom Lambda** for raw events. The two Lambda
forms are alternatives, not layers. Build commands prepare artifacts but do not deploy them.

## Node

```sh
brix build --platform node
HOST=0.0.0.0 PORT=3000 brix start

```

`brix start` imports the named `app` export from an existing `dist/app.mjs`. Keep the complete `dist`
directory and the exact project installation together. It defaults to host `0.0.0.0`, port `3000`,
and `NODE_ENV=production` when unset; an invalid `PORT` fails at startup.

`brix start` does not load environment stages itself. When `defineBrixServer` receives `env`, as
in generated applications, the server reads the snapshot on the first request and reuses it, from
one of two sources:

- an uploaded AWS snapshot named by both `SECRETS_ARN` and `SECRETS_VERSION`, the normal
  production choice (see [environment secrets](/docs/environment-secrets.md));
- a stage resolved by Brix for local verification, as in
  `brix env run staging --no-local -- start` (see
  [start a production build locally](/docs/environment-loading.md#start-a-production-build-locally)).

Without either, or with only one of the two AWS variables, every request returns a generic 500
response; the cause is not exposed to clients. Smoke one request after starting the process.

Behind a TLS-terminating load balancer, reverse proxy, or ingress, the Node socket is plain HTTP, so
request URLs would otherwise start with `http://`. Set `BRIX_PUBLIC_ORIGIN` to the trusted public
HTTPS origin, for example `https://www.example.com`, with no credentials, path, query, or fragment;
an invalid value fails at startup. `brix start` then builds every request URL from that origin and
the request path, ignoring the socket scheme, the `Host` header, an absolute request target, and
forwarded headers. Same-origin checks such as the Contentful client-loading endpoints, redirects, and
render data `baseUrl` see the public origin. Serve one public origin per process when you set it.

On `SIGTERM` or `SIGINT`, `brix start` stops accepting connections, closes idle keep-alive
connections, lets in-flight requests (including streamed responses and their request-log flushes)
finish, and then exits as terminated by that signal. `BRIX_SHUTDOWN_TIMEOUT_MS` (default `10000`)
bounds that drain; remaining connections are then closed. Another signal more than one second
after the first closes them at once; the duplicate `SIGINT` a terminal Ctrl+C delivers through the
launcher does not cut the drain short.
Keep the supervisor's grace period, such as Kubernetes `terminationGracePeriodSeconds` or the ECS
stop timeout, longer than the drain. Keep-alive sockets stay open for `BRIX_KEEP_ALIVE_TIMEOUT_MS`
(default `65000`), longer than the 60-second idle timeout of common load balancers such as AWS ALB,
so the balancer closes idle connections first; keep this value above your balancer's idle timeout.
Both values are whole milliseconds; invalid values fail at startup.

`brix start` and the generated Lambda handler send uncompressed responses: Brix applies no gzip or
Brotli to HTML, JSON, or assets. AWS ALB and API Gateway HTTP APIs do not compress either. Put a
compressing CDN or reverse proxy in front, and confirm it also compresses uncached dynamic HTML
(for example, a CloudFront cache policy with caching disabled does not compress).

Expected result: the production server serves the same discovered routes and assets inspected before
the build. Smoke a page, API response, and asset before packaging it for a process manager or container.

## Generated HTTP Lambda

```sh
brix build --platform lambda

```

Without a custom `handler` option, this builds the complete generated HTTP application in
`dist/app.mjs` and emits `dist/deployment/package.zip`, `deployment.json`, and `assets/`.

All delivery files are together under one directory:

```text
dist/deployment/
├── package.zip
├── deployment.json
└── assets/

```

Set `platform: "lambda"` in `defineBrixConfig` to use plain `brix build`. In a workspace, use
`brix build#backend` for that application. No deployment config, packaging command, AWS credentials,
or Terraform installation is required for artifact preparation.

Deploy the generated `dist/deployment/package.zip` using the manifest's `runtime.handler`
(`app.handler`). Do not repackage the repository. A source wrapper around `src/app.ts` would bypass
generated route and island assembly. The DynamoDB data-cache adapter is supported only on
`platform: "lambda"`. Its optional `strong: true` enables consistent reads; invalidation remains
eventual. For oversized values, configure optional [S3 overflow](/docs/caching-stores.md#store-oversized-values-in-s3)
with a separately provisioned bucket, restricted permissions, and lifecycle cleanup.

When API Gateway's hostname differs from the public viewer hostname, set `BRIX_PUBLIC_ORIGIN` on the
Lambda to the trusted public origin, for example `https://www.example.com`. The value must be an
HTTPS origin with no credentials, path, query, or fragment, and requires API Gateway HTTP API v2
events; an invalid value fails at cold start, and any other event fails that invocation. Brix uses this deployment-owned value for request URL construction and ignores untrusted
forwarded-host headers. Preserve the setting when adopting existing Lambda resources into
consumer-owned Terraform.

When only another service, such as an edge, may call the Lambda, enable `serviceSignatures` in
`defineBrixConfig`. The generated handler verifies each request's [signature](/docs/service-signatures.md)
on the raw event, before the `BRIX_PUBLIC_ORIGIN` rewrite, and answers 401 to unsigned or invalid
requests and to requests whose routed path would be neither the signed one nor its decoded form. The accepted `owner/name` purposes, such as `brix/edge-origin`, are
configured in code; their keys come from `BRIX_SERVICE_VERIFY_KEYS` in the application's AWS snapshot, so
changing them is a new `SECRETS_VERSION`. The handler loads them when the Lambda starts, so a snapshot
without valid keys fails the function's initialization instead of serving requests. Signed
applications route exactly on the decoded path: `/admin/` never reaches a route for `/admin`, and
`/s%C3%B6k` reaches `/sök` (see
[exact routing](/docs/service-signatures.md#exact-routing)). Such a build is served only by its Lambda
handler: the application refuses requests that did not pass through it, and `brix start` refuses to
serve it.

## Consumer-owned Lambda delivery

Use `verifyDeploymentArtifact` from Node-only `brix/artifacts` before publishing and again before
apply; see [Terraform-first deployment](/docs/deployment-terraform.md). Its source project guard is
the application workspace path, not the manifest's entry filename. The editable AWS example covers
custom workers without browser assets; generated HTTP applications need project-owned asset delivery.
Prepare all application environments before uploading any, persist tokens and receipts, and bind
their exact ARN/version pairs through Terraform. The CLI requires explicit `--account` and `--region`.

`deployment.json` schema 1 declares target `aws-lambda`; runtime name `nodejs24.x`, handler
`app.handler` or `handler.handler`, and architecture `x86_64`; the package's relative path, size,
SHA-256 hex, and SHA-256 base64; build application, producer, Git source or `null`, and manifest
SHA-256; and assets sorted by code point. Each asset records its path inside `assets/`, public URL,
content type, cache control, size, and SHA-256. Content types follow Hono's standard extension table
(for example AVIF, PDF, XML, fonts, and source maps); unknown extensions use
`application/octet-stream`. Git source is recorded for symlinked project paths too; it is `null`
outside a Git checkout or when the project lies outside the repository. Custom workers have an empty asset list. The runtime ZIP excludes
public assets.

Generated HTTP assets receive a fresh release UUID prefix on an ordinary build while preserving the
configured local or absolute-CDN `assetPrefix`. Root public files such as `favicon.ico` retain root
URLs and conservative caching. URLs describe browser delivery, not S3 or other storage keys.
The authored public directory defaults to `public/`; configure `vite: { publicDir: "static" }`
in `defineBrixConfig` to change it, or `publicDir: false` to omit it. Custom workers do not capture
public files. Only generated browser assets and the selected public directory enter `assets/`.

Consumer CI must verify the manifest and uploaded bytes, map the files to its own
storage layout, upload assets before activating the runtime, smoke the candidate, and retain all
runtime, asset, and exact environment versions needed for rollback. Consumer infrastructure owns
environment bindings, IAM, traffic, retention, cleanup, and SSG output. Builds and artifact
verification need no deployment credentials. Explicit snapshot uploads use the caller's identity;
Brix does not orchestrate Terraform or claim atomic infrastructure activation.

Promote the same build output through delivery rather than rebuilding it: each fresh HTTP build
gets a new release URL prefix. Runtime environment snapshots are bound separately by the consumer.
If you configure a stage-specific CDN origin or intentionally load build-time environment values,
that output is specific to those inputs. A build targeting Lambda does not itself select production.

In consumer Terraform, decode `dist/deployment/deployment.json` with `jsondecode(file(...))`.
Use `runtime.name`, `runtime.handler`, and `[runtime.architecture]` for the Lambda resource's
`runtime`, `handler`, and `architectures`. Use `package.sha256Base64` as `source_code_hash`;
use the prepared ZIP directly or upload it to your own versioned artifact bucket. The manifest
does not choose an AWS resource name, account, region, bucket, or deployment stage.

For each asset, read bytes from `dist/deployment/assets/<path>`, verify `sha256`, and preserve
`contentType` and `cacheControl` during upload. Configure your CDN to serve them at `publicUrl`
and to compress them along with the Lambda's uncompressed HTML and JSON responses.
Root URLs belong to the application origin; absolute URLs name a separate asset origin.
Stable public files are not release-isolated, so changes to them must remain compatible with
the active and rollback runtime versions or be versioned by the application.

When adopting existing Lambda resources, move or import their state into your Terraform with
reviewed `moved` blocks or state moves and confirm a no-destroy plan before switching CI to
`dist/deployment/deployment.json`. Keep active versions, assets, and exact environment snapshots
until the new path is verified; see [Terraform-first deployment](/docs/deployment-terraform.md).

## Custom Lambda handlers

Declare a custom entry instead of a generated HTTP application:

```ts
// vite.config.ts
import { defineBrixConfig } from "brix/vite";

export default defineBrixConfig({ platform: "lambda", handler: "src/handler.ts" });

```

`brix build` produces a fully bundled Node `dist/handler.mjs` with named export `handler`.
This **replaces** HTTP assembly: routes, islands, and Panda are not built. The entry must live
inside `src` and export exactly one runtime value named `handler`; type-only exports are allowed.
Deploy `dist/deployment/package.zip` and read Terraform's Lambda `handler` from
`deployment.json`: it is `"handler.handler"`, not `"app.handler"`. The manifest's asset list is empty.

```ts
// src/handler.ts
import { defineLambdaHandler } from "brix/lambda";
import { env } from "#brix/env";
import { createEventHandler } from "./event-handler";

export const handler = defineLambdaHandler({ env, create: createEventHandler });

```

The factory takes injected configuration and returns an async handler. For example, with `STAGE`
declared in your environment schema:

```ts
// src/event-handler.ts
import type { CoercedEnvSchema } from "./env.generated.d.ts";

export function createEventHandler(env: Pick<CoercedEnvSchema, "STAGE">) {
  return async (event: { jobId: string }, context: { awsRequestId: string }) => ({
    jobId: event.jobId,
    requestId: context.awsRequestId,
    stage: env.STAGE,
  });
}

```

The wrapper preserves raw event/context and result types; it does not synthesize HTTP requests.
Only the declared custom entry may import `brix/lambda`. Keep HTTP routes on `c.env` and scripts
on `#brix/env/script`.

### Environment and tests

`#brix/env` is an inert declaration. Imports and builds do not resolve providers. The first
invocation lazily loads the exact `SECRETS_ARN`/`SECRETS_VERSION` snapshot and initializes the
factory. Concurrent calls share initialization; success is cached, and initialization rejection
permits a later retry. Both selectors are mandatory, with no `AWSCURRENT`, ambient application-value
override, or Varlock fallback. Publish the validated snapshot and grant the Lambda workload access
to its exact version; see [environment secrets](/docs/environment-secrets.md).

Normal tests call `createEventHandler({ STAGE: "test-run" })` with raw event/context fixtures and assert
the result, without provider access. Wrapper tests and real Lambda invocations can exercise the
exact snapshot boundary. **Custom-handler `brix dev` is unsupported.** Use direct handler tests or
an event runner; Brix does not provide an event emulator or require an HTTP wrapper for events.

### Custom Hono application

For an application-owned Hono app, use its injected factory through the supported adapter:

```ts
// src/handler.ts
import { handle } from "brix/hono/aws-lambda";
import { defineLambdaHandler } from "brix/lambda";
import { env } from "#brix/env";
import { createCustomApp } from "./custom-app";

export const handler = defineLambdaHandler({
  env,
  create: (resolvedEnv) => handle(createCustomApp(resolvedEnv)),
});

```

`createCustomApp` owns the app; do not substitute the pre-assembly Brix `src/app.ts` module.

Keep configured initialization inside the `create` factory rather than awaiting environment loading
at module level, and never import the script-only `#brix/env/script` loader from a handler. The
`handler` option is the only supported custom-entry build; do not add a Vite plugin that emits a
second entry.

After either Lambda path, bind the exact environment snapshot, upload assets before runtime
activation, and perform the public smoke checks in [deployment runtime](/docs/deployment-runtime.md).
