Neon Environments and Deploying
Deploy a Neon-backed project — named Cloudflare environments, environment variables, Hyperdrive credentials and tuning, cached public reads.
Deploy a project whose database provider is neon: per-environment connection strings, Hyperdrive bindings and credentials, and the deploy workflow. Start at Neon for configuration and connection modes.
Named Cloudflare deployment environments
Neon Hyperdrive projects can declare isolated Worker targets under
environments. A logical dev / prod pair on a project named attend-v2
deploys through Wrangler as attend-v2-dev and attend-v2-prod:
environments reads from either the top-level environments slot (the
preferred placement, and the one the config scaffold advertises) or the
original providers.database.environments slot shown below. Both are accepted
and behave identically; declaring the block in both places is a compile
error, because there would be no single source of truth.
To deploy one target into a different Cloudflare account, such as a client's,
set environments.<name>.accountId. The rules are the same on Neon and D1 —
see A target in another Cloudflare account.
export default defineConfig({
name: "attend-v2",
email: { provider: "cloudflare", from: "hello@attend.vip" },
bindings: {
secrets: [
{ name: "EVENT_PASS_HMAC_PEPPER_V1", required: true },
],
},
providers: {
runtime: defineRuntime("cloudflare"),
database: {
name: "neon",
config: {
connectionMode: "hyperdrive",
hyperdrive: { id: "ffffffffffffffffffffffffffffffff" },
},
environments: {
dev: {
// Wrangler worker name — required on every target, never derived.
name: "attend-v2-dev",
branch: "dev",
worker: {
env: "dev",
workersDev: true,
previewUrls: false,
vars: {
ENVIRONMENT: "dev",
BETTER_AUTH_URL: "https://attend-v2-dev.example.workers.dev",
},
requiredSecrets: [
"BETTER_AUTH_SECRET",
"EVENT_PASS_HMAC_PEPPER_V1",
],
bindings: {
hyperdrive: {
id: "11111111111111111111111111111111",
localConnectionString: "postgresql://quickback:dev-only@127.0.0.1:5432/attend_v2",
},
kv: { id: "22222222222222222222222222222222" },
rateLimits: {
RL_200_60: "734120911",
RL_1000_60: "734120912",
},
sendEmail: { name: "EMAIL" },
},
},
},
prod: {
name: "attend-v2",
branch: "production",
worker: {
env: "prod",
workersDev: true,
previewUrls: false,
vars: {
ENVIRONMENT: "prod",
BETTER_AUTH_URL: "https://attend-v2-prod.example.workers.dev",
},
requiredSecrets: [
"BETTER_AUTH_SECRET",
"EVENT_PASS_HMAC_PEPPER_V1",
],
bindings: {
hyperdrive: { id: "33333333333333333333333333333333" },
kv: { id: "44444444444444444444444444444444" },
rateLimits: {
RL_200_60: "734120921",
RL_1000_60: "734120922",
},
sendEmail: { name: "EMAIL" },
},
},
},
},
},
auth: defineAuth("better-auth"),
},
});Wrangler bindings and variables are non-inheritable. Quickback therefore emits
the generated vars, required-secret declaration, Hyperdrive, KV, rate-limit,
and Cloudflare Email blocks inside every [env.<name>] target. The base
Worker carries no deployable stateful binding and has workers_dev = false /
preview_urls = false, so a bare deploy cannot accidentally point at shared or
placeholder state.
The environment contract is intentionally exact and fails closed:
workersDev: trueandpreviewUrls: falsemust be explicit for each target.- The top-level
nameinwrangler.tomlis an inert placeholder,<name>-unselected, so awrangler deploywithout--envcannot replace a real target. No target may use it. worker.placement({ mode }or{ region }) sets that target's placement; without it, the top-levelproviders.runtime.config.placementis emitted for the target.- Each target declares its own
name(the Wrangler worker name) and no two share one. It is the deployed script's identity — Durable Object state and the migration ledger belong to it — so it is never derived. An existing project must restate the name it already deploys under. - The auth provider must currently be Better Auth. External auth needs a non-inheritable service binding, so it remains rejected until named targets can require an explicit per-environment service-binding override.
- Hyperdrive and KV IDs must be real 32-character Cloudflare resource IDs and cannot be reused between environments.
- Named environments must include a logical
devtarget. It is selected bynpm run devand must own abindings.hyperdrive.localConnectionString. Quickback emits that development-only URL only inside its named Hyperdrive block and rejects it on every other target, soprodalways resolves its deployed connection from the remote Hyperdrive ID. rateLimitsmust contain exactly the binding names generated by the current feature set, with account-unique integer namespace IDs. Add or remove a rate limit and the next compile tells you which override changed. Cloudflare shares counters between every Worker on the account that uses the same ID, so pick your own IDs rather than copying the ones above, and never reuse an ID across targets or projects.requiredSecretsmust exactly match the generated runtime inventory:BETTER_AUTH_SECRET,ENCRYPTION_KEKwhen envelope-encrypted columns are present, and every custom secret declared withrequired: true. It also includes the sharedAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEYcredentials when generated Better Auth code uses SES, SNS, or AWS-backed anonymous-account upgrades; every enabled social provider'sAUTH_<PROVIDER>_CLIENT_IDandAUTH_<PROVIDER>_CLIENT_SECRET; plus the configured R2 account/access/secret env names when presigned uploads are enabled. Values remain out of source control; set them withwrangler secret put <NAME> --env dev(and again forprod).- Include
sendEmail: { name: "EMAIL" }when the generated runtime uses Cloudflare Email Service; omit it when email is not generated. - Every queue and R2 bucket the config generates needs a per-target entry
under
bindings.queues/bindings.r2Buckets, with names unique across targets — see Queues and R2 buckets per target. - Custom domains and routes are owned per target. Quickback emits no
top-level
routesblock for a named-environment project — Wrangler inherits that key, so a shared block would letdeploy -e devrebind the production hostname — and every generated source (providers.runtime.config.routes,domain, CMS/Account/Admin domains,auth.domain,api.domain, app domains and their aliases, and the derivedwebhook.{baseDomain}route) must be claimed by each environment throughdomains. Each target names its own all-in-one host withdomains.primary; none is inferred. See Named Environments for the key-by-key mapping, the single-hostnamedomainshorthand, and thedomains: 'none'workers.dev-only opt-out.
Generated npm run dev selects the dev target (wrangler dev --env dev).
Quickback omits the bare deploy script for named-environment projects and
generates explicit npm run deploy:dev / npm run deploy:prod scripts. Each
maps to its configured Wrangler environment. Apply that branch's migrations
first; migrations intentionally remain a separate target-owned step.
Projects that omit environments retain the existing wrangler.toml and
package scripts byte-for-byte. Named environments require Better Auth, plus
either Neon with connectionMode: "hyperdrive" (this page) or Cloudflare D1
(see Named deployment environments).
Quickback rejects other providers or partial binding sets instead of emitting a
Worker that can deploy but fail at runtime.
Environment variables
HTTP mode has three connection points, each read by a different tool:
| Where | File / store | Read by |
|---|---|---|
| Migrations (local/CI) | .env | drizzle-kit |
wrangler dev (local Worker) | .dev.vars | Wrangler |
| Production Worker | wrangler secret put | The deployed Worker |
The compiler emits .env.neon.example and .dev.vars.example as templates,
and gitignores .dev.vars so local secrets are never committed.
# Migrations read .env — copy the template and fill it in:
cp .env.neon.example .env
# .env holds:
# DATABASE_URL — pooled quickback (runtime) role URL
# DATABASE_MIGRATION_URL — unpooled quickback_admin role URL (optional)
# wrangler dev reads .dev.vars (NOT .env) — copy the template:
cp .dev.vars.example .dev.vars # gitignored; holds DATABASE_URL + BETTER_AUTH_SECRET
# Production: secrets live in Worker secrets, never in files:
npx wrangler secret put DATABASE_URL # pooled quickback role URL
npx wrangler secret put BETTER_AUTH_SECRETDATABASE_URL is the only connection string the Worker needs at runtime — auth
and feature queries share it. DATABASE_MIGRATION_URL is used only by
drizzle-kit: the generated drizzle.config.ts reads
process.env.DATABASE_MIGRATION_URL ?? process.env.DATABASE_URL, so migrations
run as the privileged quickback_admin role when it is set and fall back to
DATABASE_URL when it is not. Never deploy DATABASE_MIGRATION_URL to the
Worker.
Hyperdrive runtime credentials
With connectionMode: "hyperdrive", do not deploy DATABASE_URL to the
Worker. Configure the HYPERDRIVE binding with query caching disabled and keep
DATABASE_URL / DATABASE_MIGRATION_URL only in the compiler or CI
environment for Drizzle schema generation and migrations. Better Auth and
feature queries both use Hyperdrive at runtime, eliminating a second direct
Neon connection lane.
Create the config against the direct Neon host (uncheck "Connection pooling" in the Neon dashboard — Hyperdrive is the pool):
npx wrangler hyperdrive create my-app-db \
--caching-disabled \
--origin-connection-limit 60 \
--connection-string="postgresql://quickback:<password>@<endpoint>.<region>.aws.neon.tech/neondb?sslmode=require"--caching-disabled is mandatory: Hyperdrive keys its cache on query text
alone and never invalidates on write, so a cached SELECT would be replayed
to another tenant. --origin-connection-limit is the soft cap on connections
Hyperdrive opens to Neon (minimum 5; about 100 on a paid Workers plan). Each
in-flight request holds one origin connection per leased client, so size it
to your concurrency, not your statement count. Raise it later with
npx wrangler hyperdrive update <id> --origin-connection-limit <n>.
Tuning the Worker for Hyperdrive
- Set placement. Every authenticated request makes several sequential
round trips (session, membership, the query), so Worker-to-database
distance dominates latency: a single
SELECTmeasured ~180 ms from the caller's colo and ~90 ms withplacement.regionset to the database region. Setproviders.runtime.config.placement: { region: "aws:us-east-2" }(your Neon region; see runtime options), or per target withenvironments.<name>.worker.placement. The compiler warns when a Hyperdrive project has neither. - Keep the session cookie cache on. It is on by default
(
session.cookieCache, 300 s) and removes the session + user lookups — two of the three fixed statements on every authenticated request. See Session handling before turning it off. - Check Neon autosuspend. Hyperdrive keeps origin connections warm, but it does not keep an idle Neon compute awake: the first request after a suspend pays the compute start. Lengthen or disable autosuspend on the production branch.
Cached public reads: a second Hyperdrive binding
Hyperdrive's query cache keys on query text and parameters alone and never
invalidates on write, so it cannot sit under the claims-scoped HYPERDRIVE
binding. It can serve public, tenant-free data through a second binding
whose database role can see nothing else. Opt a resource in with
read.cache:
// features/venues/venues.ts
import { q, defineTable } from "@quickback/compiler";
export const venues = q.table("venues", {
id: q.id(),
name: q.text().required(),
city: q.text().required(),
...q.audit(),
...q.softDelete(),
});
export default defineTable(venues, {
firewall: { exception: true },
read: {
access: { roles: ["PUBLIC"] },
cache: "hyperdrive",
},
});GET /api/v1/venues, GET /api/v1/venues/:id and its named views then read
through HYPERDRIVE_CACHED as quickback_reader, a role the security
migration creates with one privilege: SELECT on the tables that declared
read.cache, each with a USING (true) SELECT policy for that role. The
cache can only ever hold rows that role can read, so cache safety is
structural, not a property of any query. Everything else (writes, actions,
every other table) stays on HYPERDRIVE.
The compiler refuses read.cache unless all of these hold:
- Postgres over Hyperdrive on the Cloudflare runtime.
hyperdrive.cached: { id }on the provider config, orbindings.hyperdrive.cachedon every named environment.firewall: { exception: true }— no tenant or owner row filter.read.accessis a roles-only tree that admitsPUBLIC. Record predicates, relationship / permission arms, principals and function-form access are rejected.- No FK display columns and no
includeon the resource — the reader role holds no grant on other tables.
Masking still applies per caller after the query. Reads can be stale for up
to the cached config's max_age (default 60 s, --max-age to change it;
--swr extends serving-while-revalidating). Server-Timing counts these
statements and the cached connection's open under stmts / cold.
Set it up once per database:
# 1. The security migration created quickback_reader NOLOGIN; give it a login.
psql "$DATABASE_SETUP_URL" -c "ALTER ROLE quickback_reader LOGIN PASSWORD '<reader-password>';"
# 2. A second Hyperdrive config, caching ON, as that role.
npx wrangler hyperdrive create my-app-db-cached \
--max-age 60 \
--connection-string="postgresql://quickback_reader:<reader-password>@<endpoint>.<region>.aws.neon.tech/neondb?sslmode=require"database: defineDatabase("neon", {
connectionMode: "hyperdrive",
hyperdrive: {
id: "<hyperdrive-config-id>",
cached: { id: "<cached-config-id>" },
},
}),With named environments, declare bindings.hyperdrive.cached: { id } on
every target; the dev target also needs
cached.localConnectionString (the reader role's local URL), as does the
provider-level hyperdrive.cached whenever hyperdrive.localConnectionString
is set — wrangler dev connects the cached binding as quickback_reader,
and the quickback role's URL reads nothing through it. The emitted
createCachedDb(env) is read-only by construction: a write or a
db.transaction() on it throws before reaching the database.
For local wrangler dev without named environments, set
providers.database.config.hyperdrive.localConnectionString to a local or
development-only Postgres URL. With named environments, put it on the target
selected by the generated local dev script instead:
environments: {
dev: {
worker: {
bindings: {
hyperdrive: {
id: "11111111111111111111111111111111",
localConnectionString: "postgresql://quickback:dev-only@127.0.0.1:5432/attend_v2",
},
},
},
},
}Quickback requires the logical dev target, rejects the top-level local
override when named environments exist, and rejects localConnectionString
on staging or production targets. Wrangler uses this field only for local
development; deployed Workers obtain their
connection string from the Hyperdrive configuration identified by id.
The generated setup uses three Postgres roles: quickback_owner (NOLOGIN object
owner for the app/auth schemas), quickback_admin (migration/setup actor — use
its unpooled URL for DATABASE_MIGRATION_URL), and quickback (the Worker
runtime role, the only deployed DB role — use its pooled URL for
DATABASE_URL). The first generated migration bootstraps these roles as
NOLOGIN; enable login and set passwords before use. It also gives quickback
statement_timeout, idle_in_transaction_session_timeout and (PostgreSQL 17+)
transaction_timeout — see Worker-role timeouts.
Full walkthrough in the generated docs/neon-setup.md.
Run the first db:migrate with your database owner credential (Neon's
neondb_owner) — that bootstrap run also grants quickback_admin everything
the Drizzle journal needs (CREATE on the database, plus ownership of the
drizzle schema and drizzle.__drizzle_migrations). Routine migrates after
bootstrap — applying new schema deltas — then run entirely as quickback_admin
via DATABASE_MIGRATION_URL, no owner credential required. This includes the
pinned runner's CREATE SCHEMA IF NOT EXISTS drizzle preamble, which needs
database-level CREATE even as a no-op and previously forced every migrate
back onto the owner credential. (A change to the security/RLS config appends
a new quickback_rls migration that re-runs the role bootstrap, so re-point
DATABASE_MIGRATION_URL at the owner credential for that one apply.)
Each security migration first removes direct PUBLIC and quickback runtime
privileges from the Drizzle schema, journal table, journal sequences, and
database-level CREATE, then restores the migration role's capability. The
audit schema/table likewise revoke prior direct grants before restoring only
runtime schema usage + table INSERT and admin forensic access. Reapplying a
migration therefore converges privilege drift instead of merely adding grants.
The role bootstrap's ownership sweep re-owns tables, views, materialized
views, and standalone sequences to quickback_owner, but skips sequences
linked to a serial/identity column — Postgres forbids re-owning those
independently (their ownership follows the table's automatically), so serial
columns never break a security migration.
The audit schema is latched: once a project has emitted it, every later
compile keeps emitting it even if no unsafe / PUBLIC / hard-delete action
remains — the compiler never generates DROP SCHEMA audit, and the audit
subsystem's CREATE statements are hardened to IF NOT EXISTS so
re-application can never collide. audit.events is an append-only forensic
sink; purging it is a deliberate operator action, never a generated migration.
Deploying
Projects with no custom domain
A Worker that lives only on workers.dev (no providers.runtime.config.routes,
no domains) must tell the generated auth layer its own host. Without it the
JWT issuer defaults to the local dev URL and cookie-backed browser mutations are
refused as cross-site:
npx wrangler deploy \
--var EXTRA_APP_HOSTS:<name>.<account>.workers.dev \
--var BETTER_AUTH_URL:https://<name>.<account>.workers.devNamed environments set BETTER_AUTH_URL in worker.vars (see above);
EXTRA_APP_HOSTS is documented under
Multi-domain architecture.
For an unnamed target, the generated deploy script runs migrations, then
ships the Worker:
npm run deploy # runs db:migrate (drizzle-kit) then wrangler deployHTTP mode reads DATABASE_URL in the Worker, so set both runtime secrets before
its first deploy:
npx wrangler secret put DATABASE_URL # pooled quickback role URL
npx wrangler secret put BETTER_AUTH_SECRETThe generated HTTP client fails fast at boot if DATABASE_URL is missing.
Hyperdrive mode gets its runtime connection string from the HYPERDRIVE
binding and must not receive a Worker DATABASE_URL secret. Its
DATABASE_URL / DATABASE_MIGRATION_URL values remain local or CI migration
inputs only. Set BETTER_AUTH_SECRET and any other exact generated secret
inventory, then deploy:
npx wrangler secret put BETTER_AUTH_SECRET
npm run deployNamed Hyperdrive targets intentionally omit the bare deploy script and keep
the base Worker non-deployable. Apply the target branch's migrations, set each
secret with --env dev or --env prod, then use an explicit target:
npx wrangler secret put BETTER_AUTH_SECRET --env dev
npm run deploy:dev
npx wrangler secret put BETTER_AUTH_SECRET --env prod
npm run deploy:prodLive runtime smoke testing against a deployed Neon Worker is still being brought up; the compile/typecheck/migrate path is verified end-to-end (including executing the generated Postgres migrations under pglite), but treat a first production deploy as you would any new stack — exercise auth, a CRUD flow, and a batch write before relying on it.
Neon
Use Neon serverless PostgreSQL with Quickback — configuration, connection modes, capability limits, and when to choose Neon over D1. RLS, migrations, environments and transactions have their own pages.
Neon Row Level Security
Worker-scoped RLS on Neon — the set_config claim model, generated policies, the soft-delete lane, delegated principals, relationship arms and helper functions.