--- title: "Going to production" description: "Take a Beignet app to production: preflight checks, env validation and secrets, host settings, runtime entrypoints, and the pre-launch security checklist." url: "https://www.beignetjs.com/deployment" markdown_url: "https://www.beignetjs.com/markdown/deployment.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Going to production Beignet gives production apps guardrails, but it does not make deployment or security automatic. Treat this page as the pre-launch checklist: run the preflight checks, validate configuration, verify host settings, wire bounded runtime entrypoints, and confirm the security posture of every exposed surface. For a concrete first deployment, follow [Deploy a Next.js app](https://www.beignetjs.com/markdown/guides/deploy-nextjs.md) to put the SQLite starter on Vercel with a hosted Turso database. ## Preflight checks For Next.js apps, use Next.js 15.5.28 or newer within v15, or 16.4.1 or newer within v16. Keep its image-processing dependency Sharp at 0.35.5 or newer. These releases address the [image-optimization vulnerability](https://github.com/advisories/GHSA-2464-fhr4-w9xw), the [`use cache` vulnerability](https://github.com/advisories/GHSA-673q-mjm6-r5xr), and [Server Action denial of service](https://github.com/advisories/GHSA-p3m5-59mp-jv5r). Run the validation loop in CI before shipping: ```bash bun beignet check ``` It runs `beignet lint`, `beignet doctor --strict`, and the app's `lint`, `typecheck`, and `test` scripts in one pass, and exits non-zero when any step fails. Run `bun run format` locally before opening a change. `beignet lint` enforces dependency direction so sensitive infrastructure code does not leak into domain, use case, route, or component layers. `doctor --strict` is the CI bar: it catches production drift that is easy to miss during manual edits, such as exposed devtools routes, missing cron auth, upload definitions without explicit size limits, provider environment variables that are not configured, and credentialed wildcard CORS. For GitHub-annotation output, run `beignet lint --format github` and `beignet doctor --strict --format github` individually. In the deploy pipeline itself — where production configuration is present — run the runtime gate: ```bash bun beignet preflight ``` It validates the actual environment: required provider env vars, secrets still matching `.env.example` placeholders, the app env schema, doctor's production hardening findings, and logging/error-reporting wiring. Missing or statically unresolved upload authorization fails this gate. Add `--connect` to run the app-owned migration status check before server boot, then run every port's `checkHealth()` so pending migrations or a bad credential fail the deploy instead of the first request. Older apps without `db:status` receive a compatibility note and continue. Use `beignet check --preflight` to append only the disconnected environment gate to the full validation loop, or `beignet check --preflight-connect` to include migration status and dependency health checks. Both connected commands accept `--connect-timeout-ms ` when the default 5000 ms per check is too short. Confirm the CLI can inspect the route map: ```bash bun beignet routes ``` If your app exposes OpenAPI, make sure the OpenAPI route imports the static `contractsFromRoutes(routes)` export from `server/routes.ts`. Run `doctor` after changing contracts or route registration. ## Production hardening checklist When `doctor` reports production-readiness diagnostics, use this checklist before launch: - Secrets and provider credentials are unique per environment, validated at startup, never committed, and never logged. - Auth routes, tenant resolution, authorization policies, and trusted origins derive authority from verified sessions, API keys, or trusted gateway metadata. - Devtools, OpenAPI, cron, webhooks, and operational routes have intentional exposure and app-owned authorization. - CORS origins, proxy IP trust, rate-limit keys, and request body limits match the production host topology. - Uploads and storage define max sizes, authorization or explicit public access, object visibility, safe content headers, and short direct-upload expirations. - Provider-backed dependencies have bounded readiness checks, worker shutdown behavior, webhook secrets, and least-privilege credentials. ## Environment variables and secrets Apps storing encrypted fields must provision the same key ring to every reader, including workers and operational tasks. Follow [Encryption](https://www.beignetjs.com/markdown/encryption.md#rotate-keys) for rolling rotation, rollback, and backup recovery; never generate a new key on boot. Keep deploy-time configuration in `lib/env.ts` with `@beignet/core/config` and validate it at startup. Avoid reading ad hoc environment variables inside route handlers, use cases, or infra adapters. Declare server-only and client-safe variables separately: ```typescript import { createEnv } from "@beignet/core/config"; import { z } from "zod"; export const env = createEnv({ server: { NODE_ENV: z.enum(["development", "test", "production"]), CRON_SECRET: z.string().min(32), BETTER_AUTH_SECRET: z.string().min(32), STORAGE_S3_BUCKET: z.string().min(1), }, clientPrefix: "NEXT_PUBLIC_", client: { NEXT_PUBLIC_APP_URL: z.string().url(), }, runtimeEnv: process.env, }); ``` Rules: - Never put secrets behind the client prefix. - Validate required production secrets at startup. - Prefer platform secret stores over committed `.env` files, and keep `.env.example` useful but empty of real values. - Use `runtimeEnvStrict` when the host only bundles variables that are explicitly referenced. See [Config](https://www.beignetjs.com/markdown/config.md) for the strict runtime helpers. Provider credentials should be owned by the deployment environment and read through app config. Scope database and S3-compatible credentials to the app, environment, and narrowest bucket or key prefix possible, and never log, audit, or record credentials in devtools. `doctor --strict` checks common first-party provider environment variables when the corresponding package is installed. ## Host settings Before launch, verify the host configuration: - `NODE_ENV=production` is set for production builds. - TLS is enforced by the platform. - Preview and production environments have separate secrets and databases, and do not share writable credentials unless that is intentional. - The database pool maximum is budgeted across the host's maximum web, worker, preview, task, and migration concurrency. Serverless deployments use a provider-managed pooled endpoint when available. - BullMQ Redis uses `maxmemory-policy=noeviction`, appropriate persistence, memory alerts, and bounded completed/failed job retention. Queue payloads do not contain secrets or unnecessary personal data. - Cron routes receive the expected `Authorization` header. - Build logs do not print secrets. - `requestBody.maxBytes` and upload router `limits` match the largest expected JSON, direct-upload metadata, and server-handled multipart requests. - OpenAPI and devtools routes have the intended exposure. - Source maps, stack traces, and error reporting settings match the team's incident response plan. ## Safe database migrations Generate and commit migration files before deployment. For each environment, run one serialized release job: ```bash bun beignet db migrate bun beignet db status bun beignet preflight --connect ``` Use the deployment platform's environment or concurrency lock so two releases cannot migrate the same database at once. Do not run migrations from every web replica, a readiness route, or application startup. `db status` is observational and cannot close the race between inspection and migration; serialization is the safety mechanism. If the platform cannot serialize release jobs, wrap the app-owned migration script in a database advisory lock appropriate to the selected backend. Rolling deploys should use expand-and-contract migrations: deploy additive, backward-compatible schema changes first, roll out compatible application code, and remove old columns or constraints in a later release after every old instance has stopped. ## Liveness and readiness Keep liveness and readiness separate: - `/api/health` should be cheap and local. It answers whether the process can respond. - `/api/ready` should run bounded dependency checks. It answers whether the app should receive traffic. Generated apps expose both endpoints. The readiness route uses `createHealthRoute(...)` from `@beignet/next` and provider-owned checks such as `ctx.ports.db.checkHealth()`: ```ts // app/api/ready/route.ts import { createHealthRoute } from "@beignet/next"; import { env } from "@/lib/env"; import { getServer } from "@/server"; export const { GET } = createHealthRoute( getServer, { checks: { database: (ports) => ports.db.checkHealth(), }, timeoutMs: 2000, }, env.NODE_ENV, ); ``` Readiness checks should be cheap, non-mutating probes such as `select 1`, Redis `PING`, queue health checks, or a provider health endpoint. Do not run migrations, drains, workers, or polling loops from readiness routes. `doctor` only checks for the presence of app-owned readiness wiring; it does not make network calls. First-party Drizzle, Redis cache, Redis event bus, Redis locks, Upstash rate limiting, BullMQ jobs, Meilisearch, S3-compatible storage, and Vercel Blob storage providers expose explicit `checkHealth()` helpers for this purpose. ## Security headers, CORS, CSRF, and client IPs Install the browser response-header baseline in `server/index.ts`: ```ts import { createSecurityHeadersHooks } from "@beignet/core/server"; const hooks = [ createSecurityHeadersHooks({ contentSecurityPolicy: "default-src 'self'; frame-ancestors 'none'", strictTransportSecurity: env.NODE_ENV === "production" ? { maxAgeSec: 31_536_000, includeSubDomains: true } : false, }), ]; ``` The hook adds common response headers and preserves route-owned headers. Keep CSP and HSTS explicit because asset hosts, embedded frames, redirects, and HTTPS rollout are app-owned deployment decisions. `doctor` warns when the central server does not install `createSecurityHeadersHooks(...)`. For credentialed browser requests: - Do not combine `credentials: true` with `origin: "*"` or `origins: ["*"]`. Use an explicit origin allow-list per environment. Beignet rejects this configuration in `createCorsHooks(...)`, and `doctor` warns about the same pattern before deploy. - Keep cookies `HttpOnly`, `Secure` in production, and `SameSite=Lax` or `SameSite=Strict` unless your auth flow requires cross-site cookies. For cookie-backed browser mutations, install `createCsrfHooks(...)`; keep provider webhooks and auth callbacks on explicit `skip` rules when another verifier owns the route. - CORS hooks short-circuit only browser preflights that include `Origin` and `Access-Control-Request-Method`; explicit `OPTIONS` contracts remain routable. ```ts import { createCsrfHooks } from "@beignet/core/server"; const csrf = createCsrfHooks({ allowMissingOrigin: false, trustedOrigins: ["https://app.example.com"], token: { cookieName: "csrf", headerName: "x-csrf-token", }, skip: ({ contract }) => contract.name.startsWith("webhooks."), }); const server = await createNextServer({ trustedProxy: { clientIp: "x-forwarded-for-last", }, hooks: [csrf, createRateLimitHooks()], // ... }); ``` Any control keyed by client IP is only as trustworthy as the header it reads. Clients can send arbitrary `x-forwarded-for` values; only the entry appended by your platform's trusted reverse proxy is reliable. Configure an explicit server-level `trustedProxy.clientIp` for IP-scoped limits; otherwise Beignet requires a custom `earlyKey` or explicit `ipSource: "none"` opt-out. The same policy lets `createCsrfHooks(...)` compare browser origins against external forwarded host and protocol values, and it supplies resolved `requestInfo` to the app context and logging hooks. See [Rate limiting](https://www.beignetjs.com/markdown/rate-limiting.md) for the trusted-proxy details and key strategies. ## Providers Production providers should be installed in `server/providers.ts` when your app has that file, or directly in the central server setup. Provider startup and teardown belong to the application lifecycle, not route handlers. Use `beignet provider add ` for supported provider recipes such as OpenFeature flags, mail, Meilisearch search, Sentry error reporting, Upstash rate limiting, Redis cache, Redis event bus, Redis locks, and S3-compatible storage. The command writes dependency, provider, port, env, and setup-note changes that `beignet provider audit` and `beignet doctor --strict` can inspect. Check these before shipping: - Database clients and migrations are ready for the target environment. - Better Auth and the Beignet database provider share one module-scoped client when they use the same database; generated apps keep it in `infra/db/client.ts`. - Cache, mail, job, auth, logging, and rate-limit providers have required env. - Unit of Work and after-commit event behavior are tested with the real adapter. - Dev-only providers and devtools routes are gated appropriately. For durable workflows, verify each provider's failure semantics before relying on it in production: outbox adapters should preserve attempts, retry timing, leases, and dead-letter state, and job providers should document which retry behavior they own. In-memory providers are for tests, local development, or single-process apps; they are not a substitute for queues, workers, or durable outbox drains. Mail providers intentionally fail fast because sends are not idempotent; retry mail through jobs or outbox rows that own idempotency. Redis Pub/Sub event delivery is best-effort and cross-process, but it does not persist, replay, acknowledge, retry, or dead-letter event messages. The env-backed event-bus provider uses two connections per process and targets a standalone or managed single Redis endpoint. Run subscribers in long-lived processes; reconnect restores subscriptions but cannot recover events published while disconnected. Sentinel and Cluster deployments should inject app-owned ioredis clients and prove failover behavior against the selected host. Failed initial subscriptions retry with capped backoff while their listeners remain registered. S3-compatible storage delegates bounded transient retries to the AWS SDK when the provider creates the client; injected clients keep their own retry configuration. ## Runtime recipes Background and operational work should run from explicit bounded entrypoints. The web process should serve HTTP, cron routes should trigger one unit of work, workers should own repeated or queue-backed work, provider-backed function hosts should own provider invocations, and tasks should run from operator or CI commands. Do not start polling loops, queue consumers, or interval drains from provider `setup` or `start` hooks in serverless apps. Provider hooks should install ports, prepare clients, run bounded startup checks, and close resources. The host should decide when to invoke the work. See [Runtime recipes](https://www.beignetjs.com/markdown/runtime-recipes.md) for the concrete layouts: web-only apps, cron routes, outbox drains, BullMQ workers, Inngest functions, `beignet schedule run`, `beignet outbox drain`, `beignet task run`, and provider readiness checks for Redis, S3-compatible storage, search, queues, and databases. ## Devtools Devtools are for local development by default. HTTP routes remain hidden until you configure authorization, and non-development environments additionally require explicit enablement. If you enable devtools in staging or an internal environment, add an `authorize` callback, keep event retention short, and redact sensitive fields before recording custom events. Beignet's doctor warns when a devtools route has no access policy. See [Devtools](https://www.beignetjs.com/markdown/devtools.md) for the route options and local-only unauthenticated opt-in. ## Uploads and storage Every upload definition should set explicit file constraints: allowed content types, `maxSizeBytes`, and visibility. Uploads are protected by default, so add `authorize(...)` unless the workflow is intentionally public and declares `access: "public"`. Keep object keys tenant- or owner-scoped, default to private visibility, and keep direct-upload expiration windows short. Beignet's doctor warns when feature-owned upload definitions omit `maxSizeBytes` or authorization. See [Uploads](https://www.beignetjs.com/markdown/uploads.md) and [Storage](https://www.beignetjs.com/markdown/storage.md) for definition options, signature verification, checksums, scanner hooks, and object ownership. Public storage routes set `nosniff` and download active content types by default; keep that default unless the app intentionally serves active public assets from the application origin. ## Logging, audit, and redaction Logs, audit entries, and devtools events should help operators debug without leaking secrets or sensitive domain data. Use the shared `redactValue` and `redactHeaders` helpers from `@beignet/core/ports` for structured metadata, and store actor, tenant, request, and resource IDs instead of raw request or response bodies. Read [Privacy lifecycle](https://www.beignetjs.com/markdown/privacy-lifecycle.md) before launch to define retention, deletion, and "what not to log" rules, and [Audit and activity logging](https://www.beignetjs.com/markdown/audit.md) for durable activity records. ## Client base URLs Server-side code should usually call internal functions directly. When it must use the HTTP client, pass an absolute `baseUrl` to `createClient(...)`. Browser clients can use same-origin relative requests behind the deployment platform's routing layer. Keep client construction in `client/` so base URL and auth behavior have one home. ## Related pages - [Config](https://www.beignetjs.com/markdown/config.md) for typed environment validation. - [Runtime recipes](https://www.beignetjs.com/markdown/runtime-recipes.md) for web, cron, worker, provider-function, task, and readiness layouts. - [Schedules](https://www.beignetjs.com/markdown/schedules.md), [Outbox](https://www.beignetjs.com/markdown/outbox.md), [Jobs](https://www.beignetjs.com/markdown/jobs.md), and [Tasks](https://www.beignetjs.com/markdown/tasks.md) for the Beignet primitives those runtimes invoke. - [Authentication](https://www.beignetjs.com/markdown/authentication.md) and [Authorization](https://www.beignetjs.com/markdown/authorization.md) for request identity and business policy. - [Rate limiting](https://www.beignetjs.com/markdown/rate-limiting.md) for trusted client IPs and key strategies. - [Privacy lifecycle](https://www.beignetjs.com/markdown/privacy-lifecycle.md) for retention, export, deletion, anonymization, and sensitive-data boundaries. ## Broadcasting across instances Use a shared Redis broadcasting provider when publishers and browser streams run in different processes. Memory broadcasting cannot connect serverless instances or external workers. Keep one provider instance per server runtime, set a unique Redis prefix per app/environment, and configure a reliable outbox drain for publication jobs recorded alongside database writes. The host must support streaming responses and outbound Redis sockets. Broadcast streams renew after 60 seconds by default; configure `maxLifetimeMs` up to 3,600,000 ms (one hour) when appropriate. Set the host request duration above it with headroom for context creation, authorization, and cleanup. A Next.js Node route can declare `maxDuration = 120` for a 60-second stream, subject to platform and plan limits, or `maxDuration = 300` for a four-minute stream. Longer streams also increase the interval between authorization checks. The ioredis provider is not an Edge adapter. Reconnection triggers query reconciliation, so measure renewal traffic, database reads, connection counts, memory, latency, and cost under expected load. See [Broadcasting](https://www.beignetjs.com/markdown/broadcasting.md#deployment-and-operations).