Last updated:
Lunora apps deploy as a single Cloudflare Worker plus Durable Object class, D1 database, and R2 bucket bindings. There is nothing else to provision: no separate API service, no platform sign-up.
wrangler.jsonc
The following wrangler.jsonc declares the Worker, its Durable Object classes, the D1 database and the R2 bucket:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-lunora-app",
"main": "src/server/index.ts",
"compatibility_date": "2026-06-10",
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [
{ "name": "SHARD", "class_name": "ShardDO" },
{ "name": "SCHEDULER", "class_name": "SchedulerDO" },
// Remembers revoked named admin tokens where a restore of the shard cannot rewind them.
{ "name": "ADMIN_REVOCATIONS", "class_name": "AdminRevocationDO" },
],
},
"migrations": [
{ "tag": "v1", "new_sqlite_classes": ["ShardDO", "SchedulerDO"] },
{ "tag": "v2", "new_sqlite_classes": ["AdminRevocationDO"] },
],
"d1_databases": [{ "binding": "DB", "database_name": "my-lunora-app", "database_id": "<from-wrangler-d1-create>" }],
"r2_buckets": [{ "binding": "FILES", "bucket_name": "my-lunora-files" }],
// Required whenever a SchedulerDO is declared. The Durable Object (DO) reads its dispatch
// target from this binding on its own env — never off the schedule request,
// which would let a caller steer the callback — and refuses to enqueue
// without it, failing every ctx.scheduler.runAfter/runAt.
"vars": { "LUNORA_ORIGIN_URL": "https://my-lunora-app.example.workers.dev" },
}:::note[Vite-first apps: the scheduler wires itself]
ctx.scheduler.runAfter / runAt dispatch through a SchedulerDO, and wrangler
binds only what the worker entry exports. In a Vite-first app ("main": "virtual:lunora/worker") that entry is generated, so there is nothing to edit —
and nothing to: as soon as your app uses the scheduler (a cron, a ctx.scheduler
call, or a direct @lunora/scheduler dependency), codegen emits the class,
the generated entry exports and wires it, and lunora dev reconciles the
SCHEDULER binding and its migration into wrangler.jsonc for you.
Cron jobs never needed it: they run through the worker's own scheduled()
handler. Only deferred dispatch and the studio's scheduled-jobs view do.
One thing is still yours: LUNORA_ORIGIN_URL. The Durable Object reads its
dispatch origin from its own env and refuses to enqueue without it, so
lunora verify warns whenever a SchedulerDO is declared and that var is unset.
:::
lunora.config.ts
One optional file at the project root carries the project's Lunora settings — the
deploy target, the remote-binding dev preference, the app hook a
Vite-first project composes its worker with, and advisor.minSeverity, the
lowest advisory level codegen reports and writes into _generated/shard.ts
("info", "warn" or "error"; an ERROR is never dropped, so the codegen gate
stays on), and security.headers, the baseline security headers for the Worker
and the static assets (Configuring the
headers). It replaces lunora.json: the two
were always the same question, split across a format boundary that existed only
because the CLI could not read TypeScript. It can now (jiti), so there is one
file and it is real code.
// lunora.config.ts
import type { LunoraConfig } from "./lunora/_generated/app";
export default {
target: "cloudflare",
remote: true,
advisor: { minSeverity: "warn" },
codegen: { exclude: ["seed/**", "**/*.fixture.ts"], lazyFunctions: true },
} satisfies LunoraConfig;Codegen reads every .ts file under lunora/ as app source, except test code:
*.test.ts, *.spec.ts, *.test-d.ts, *.spec-d.ts, *.bench.ts,
*.e2e.ts and *.e2e-spec.ts files, and the __tests__/, __mocks__/,
__fixtures__/ and __snapshots__/ folders. Such files cannot register
functions, raise advisories, or appear in the architecture view.
codegen.exclude adds more globs, matched against the path relative to
lunora/ (! negations are not supported) — for example "tests/**" or
"**/test-*.ts", which are not skipped by default because a real feature
module may carry those names. Secret scanning is
the one exception: it still reads test and excluded files, because a live
vendor key committed anywhere is still a leak.
codegen.lazyFunctions: true makes _generated/functions.ts load each function
module with import() instead of importing all of them up front. Codegen reads
the key on every run, so lunora codegen, dev, prepare, verify, build,
deploy and the Vite and Rspack plugins all emit the same registry. The
--lazy-functions flag and LUNORA_LAZY_FUNCTIONS=1 turn it on for one run;
neither can turn off what the config enables.
Codegen does not parse your whole tsconfig. Its TypeScript program starts from
the lunora/ sources, the worker entry, the .d.ts files your tsconfig.json
includes, and any other tsconfig-included file whose declarations apply to the
whole program: a script, a declare global block, or a triple-slash directive.
A declare module "x" in such a file counts only when a file the program reaches
imports x. Everything else (your UI, your tests) is reached only by import, and
the tsconfig's compiler options and path aliases still apply. A project whose
tsconfig includes a large src/ no longer pays to parse it on a cold run. The
tsconfig's file list is read on a cold start, so a declaration added to src/
mid-session is picked up on the next start.
lunora.config.mts, .js and .mjs are read too, so a JS-authored project is
not forced into TypeScript for one file. .cts / .cjs are deliberately not:
Vite's default resolve.extensions does not cover them, so the specifier the
generated worker entry imports for the app hook would not resolve.
Codegen checks the file before it reads it, on every lunora dev, codegen,
build and deploy run and in the Vite and Rspack plugins. A key that is not
one of advisor, app, codegen, durableObjects, remote, security,
services, studio and target (or not one of a section's keys, down to an
advisor.accept entry), a literal of the wrong type such as remote: "true"
or rpc: true, and a file with only named exports and no export default each
stop the run with a PROJECT_CONFIG_INVALID error that names the key and the
closest valid spelling:
lunora.config.ts is invalid:
- unknown key `remot`. Did you mean `remote`? Valid keys: advisor, app, codegen, durableObjects, remote, security, services, studio, target.A computed value (remote: process.env.REMOTE === "1") is not checked, because
codegen reads the file without running it, and neither is a value in an object
that also has a spread ({ ...base, remote: true }), which the spread may
override; the key names around it still are. LunoraConfig types remote as
a boolean, but a remote: null in a file that is not type-checked is read as no
preference, the same as leaving remote out.
Every template that declares a tsconfig include lists lunora.config.ts in it,
which is what gets the file type-checked (nuxt declares none — it extends the
config Nitro generates, which already covers the project root).
The app hook
In a Vite-first app ("main": "virtual:lunora/worker") @lunora/vite generates
the worker entry, so there is no file to chain your own defineApp() calls on.
Anything mechanical is composed for you — the shard selector, and
.scheduler(...) as above. Anything that needs your code is not:
.auth(...) takes your better-auth options, .global(...) your D1 writer,
.vectors(...) your embedder, and resolveIdentity is only ever set by
.auth(), .access() or .extend().
// lunora.config.ts
import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
interface Env {
DB: D1Database;
BETTER_AUTH_SECRET: string;
}
export default {
target: "cloudflare",
app: (app: AppBuilder<Env>): AppBuilder<Env> =>
app
.auth({
d1: (env) => env.DB,
options: (env) => ({ secret: env.BETTER_AUTH_SECRET }),
})
.global({ d1: (env) => env.DB }),
} satisfies LunoraConfig<Env>;The generated entry calls the hook between the shard selector and its own
.httpRouter(...) / .build(), so the framework wiring stays with the plugin
and your capabilities are chained in the middle.
Three things are worth knowing about this file:
- Export it as
default. Both readers resolve the default export and nothing else, because the generated entry imports it as one. A hook reached through a named export is ignored. - Keep the imports type-only if you can. The
apphook is bundled into the worker, so a runtimeimporthere ships with it. It is also evaluated on the host to discover the hook, so a runtime import must resolve there too — acloudflare:*module or a tsconfig path alias (which the loader does not read) will throw, and the build warns that the hook was not composed.import typeis erased on both counts, which is why the shape above usessatisfiesrather than adefineConfig()call. - Write
target,remote,advisor.minSeverity,advisor.accept,codegen.excludeandcodegen.lazyFunctionsas literals.lunora codegenresolves the target synchronously, by parsing this file rather than running it, so a computed value, a getter or a spread is not seen. It is not silently defaulted either —lunora verifyreportsplatform_unreadable_target, and an unreadableminSeverityreportsadvisor_min_severity_invalidand filters nothing, an unreadableadvisor.acceptreportsadvisor_accept_invalidand accepts nothing, an unreadablecodegen.excludelogs a warning and excludes nothing extra, and an unreadablecodegen.lazyFunctionslogs a warning and stays eager. Aconstin the same file and a shorthand property both work.
A config that throws, or whose app is not a function, is ignored rather than
breaking the build — the entry composes as if the hook were absent. A
hand-written entry (src/server.ts, src/worker.ts) needs no hook at all: chain
the calls there directly.
Secrets
Locally
Local secrets live in .dev.vars (gitignored), which wrangler dev and the
Vite dev server load automatically. Commit a .dev.vars.example listing the
keys your worker needs:
# .dev.vars.example
AUTH_SECRET="replace-with-openssl-rand-hex-32"
AUTH_URL="http://localhost:5173"
STORAGE_SECRET="replace-with-openssl-rand-hex-32"When you run lunora dev (or start Vite) without a .dev.vars, Lunora offers
to generate one from the example. Secret-looking placeholders (*_SECRET,
*_TOKEN, and the like) are filled with fresh random values, and everything
else is copied verbatim. If .dev.vars exists but is missing keys the example
lists (e.g. you enabled a new addon), it offers to append just those.
On every lunora dev / vite dev startup, Lunora also auto-generates any
empty secret already in .dev.vars and ensures LUNORA_ADMIN_TOKEN is
present, so a project scaffolded by lunora add (which writes its secrets
blank) boots with working values and the Studio
authenticates without prompting. Only locally-generatable secrets are minted;
provider keys (RESEND_API_KEY, STRIPE_SECRET_KEY, …) stay blank for you to
paste, and a real value is never overwritten.
You can also manage keys by hand: lunora env set NAME VALUE, lunora env list,
or generate strong values explicitly with lunora env generate (see below). To
check a .dev.vars against its example for missing keys, still-unset
placeholders, and stray extras, run lunora env doctor; it exits non-zero when
anything is actionable, so it works as a CI gate or a pre-dev sanity check.
Generating strong secrets
lunora env generate mints cryptographically-strong values (32-byte hex, like
openssl rand -hex 32) for the secrets your project can generate locally. Use
them for production or any other environment:
lunora env generate # print KEY=value for every generatable secret
lunora env generate AUTH_SECRET # print one
lunora env generate --set # write them into .dev.vars instead of printingProvider-issued keys (Resend, Stripe, Polar) are skipped; you obtain those from the provider's dashboard.
In production
Cloudflare secrets are per-environment and non-inheritable. Set them for the environment you deploy to:
wrangler secret put AUTH_SECRET --env production
wrangler secret put RESEND_API_KEY --env productionOr push everything from .dev.vars at once with lunora env push --yes
(--prod targets the production environment). Pipe a freshly generated value
straight in: lunora env generate AUTH_SECRET | cut -d= -f2- | wrangler secret put AUTH_SECRET --env production.
wrangler deploy never pushes .dev.vars values, so lunora deploy checks the
target worker's secrets first:
- Interactively, it offers to generate + push any missing generatable secret before shipping, and flags provider keys for you to set by hand.
- Non-interactively (CI), a missing required secret aborts the deploy: better a failed pipeline than a worker that crashes on a missing secret. Set the secrets (the error lists them) and re-deploy.
The check is best-effort: a brand-new worker (nothing deployed yet) or an
unauthenticated wrangler can't be queried, so the deploy proceeds. Lunora never
logs secret values. Nothing else covers this: the wrangler-validator has no
notion of a "required secret" and emits no missing-secret warning, so on a first
deploy this gate is the only net, and it is the one that skips.
See Cloudflare's Secrets and Environments docs for the underlying model.
Containers
If your app declares containers, wrangler deploy
also builds each Dockerfile-backed image with your local Docker engine and
pushes it to Cloudflare's registry. lunora deploy runs a Docker preflight
first and stops with an actionable message when an engine isn't available, so
the failure is one line instead of a wrangler stack trace. Images must target
linux/amd64.
To split image build/push from the Worker deploy (e.g. across CI jobs), use the
lunora cloudflare containers wrappers:
lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push
lunora cloudflare containers images listContainer egress is billed separately from Workers. See Limits.
Deploy
Deploy the Worker from the project root:
pnpm lunora deployThis runs:
lunora codegen(no-op if up-to-date), itspostcodegenhook, and the platform-portability diagnostics- the schema-drift gate, then binding provisioning into
wrangler.jsoncandwrangler.jsoncvalidation - a Docker preflight when Dockerfile-backed containers are declared
wrangler deployagainst the resolved Worker (building/pushing container images)
Three bindings are written for you on a Cloudflare target when your code uses them and you have not declared your own:
ctx.kvgetskv_namespaces: [{ "binding": "KV" }]with noid. Wrangler creates the namespace on the first deploy and writes the id back. Declare your ownkv_namespacesentry to name it yourself. A schema that pins a.jurisdiction("…")is told to create the namespace itself (wrangler kv namespace create <name> --jurisdiction <j>), because one wrangler creates is unrestricted.ctx.sql(Hyperdrive) gets aHYPERDRIVEbinding with a placeholderid.lunora devserves it from an embedded Postgres, andlunora deploycreates the config from the connection string inLUNORA_HYPERDRIVE_URLand writes the realid, inwrangler.jsoncand in the generated config a framework build points wrangler at.lunora preparestops while the placeholder is still there.ctx.artifactsgetsartifacts: [{ "binding": "ARTIFACTS", "namespace": "<worker name>" }]. Artifacts only runs remotely, so alunora devorvite devsession without a Cloudflare login leaves the binding out (andctx.artifactsthrows if something calls it) instead of failing to start. A schema that pins a.jurisdiction("…")is told to create the namespace itself (the warning has the REST call) and add the binding, because the firstcreate()against a missing namespace makes it unrestricted for good, and a logged-in dev session would make that call. Once the binding names a namespace,lunora deploycreates it in that jurisdiction when it is missing, and stops when it is in another. That needsCLOUDFLARE_API_TOKENandCLOUDFLARE_ACCOUNT_ID. A dry run says what it would create and only warns when it cannot check, and--temporary, which deploys to a throwaway account, checks nothing and says so.
Under --migrate, the deploy applies the SQL that lunora migrate generate emits
(lunora migrate apply) and then runs the data migrations, both after the
deploy. Both require --migrate-yes for a production target and, on an unlinked
checkout, --migrate-url. A committed file that drops or replaces data also needs
--migrate-allow-destructive: --migrate-yes confirms the target and never a DROP
by itself. The SQL step takes the root admin token, or a token
minted with --scope migrations. The scoped token runs only additive files (a new
table or index, an added column); a file with a DROP, a row write or a trigger is
refused, and deploy --migrate then stops before the data migrations. A pipeline
that needs those runs deploy --migrate with the root token. A deploy tool other
than lunora deploy runs lunora migrate apply --url <worker> --yes as its own
step; see Migrations.
CI should run one of these before the deploy job, so codegen drift and a stale
_generated/ are a build failure rather than a deploy that silently ships old
types:
-
lunora prepareshares the deploy's gate pipeline — codegen, thepostcodegenhook, the schema-drift gate, binding provisioning, the D1 placeholder and container/Docker preflights, andwrangler.jsoncvalidation — so what it accepts is whatdeployaccepts. It writes (_generated/,wrangler.jsonc), so reach for it when you want the reconciled config too.It does not run migrations (step 2) or build and push images (step 4). Migrations are a deploy-time action against a live database, not a check.
-
lunora verifywrites nothing and addstsc --noEmit, so it is the lighter gate for a pull-request check.
Cloudflare CLI (cf)
Cloudflare's cf CLI is in beta, and Lunora doesn't support it yet
(#964). Lunora manages
wrangler.jsonc and deploys with Wrangler.
cfresource commands (zones, DNS, KV, …) are fine next to a Lunora project.- Don't run
cf dev,cf buildorcf deployon a Lunora project. They readcloudflare.config.ts(whichcf migratewrites), and Lunora never updates that file, so the bindings, Durable Object classes and migrations it adds later would be silently missing from those deploys.
When a cloudflare.config.{ts,mts,js,mjs} sits in the project root, Lunora warns
once per process tree — from lunora deploy, lunora codegen, lunora dev
(including --background), and the Vite and Rspack plugins on both dev and
build. A rebuild, a dev-server restart or a child process lunora dev spawned
stays quiet. lunora doctor reports it on every run as cf-config-present.
The warning never blocks: nothing lunora deploy runs reads the file.
Durable Object class limit
Cloudflare caps an account at
100 Durable Object classes on Workers Free and 500 on Workers Paid.
Every Worker that binds a class spends its own, so each environment of an app
(production, staging, previews) counts separately. A Lunora app spends up to
four framework classes: ShardDO and AdminRevocationDO always, SchedulerDO
with a scheduler, and ShardRegistryDO with .shardBy() tables. Each container and voice agent adds
one more.
lunora doctor reports how close the account is (do-class-budget-*), and
lunora deploy warns within 10 classes of a cap. Both read the count from the
Cloudflare API only when CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID (or
account_id in wrangler.jsonc) are set. The API does not say which plan an
account is on, so the check judges the count against both caps.
To spend one class instead of four, merge the framework classes before the app's first deploy:
// lunora.config.ts
export default {
durableObjects: { merge: true },
} satisfies LunoraConfig;Codegen then writes _generated/durableObjects.ts, and the generated worker
entry exports one LunoraDO class that hosts the shard, the scheduler, the
shard registry and the admin revocation store. Only the SHARD binding remains, bound to LunoraDO. The
scheduler and registry instances live in the same namespace under the reserved
__lunora_do__: name prefix, which a client-chosen shard key cannot use.
Starter templates list ShardDO (and ShardRegistryDO) in their v1
migration. Before the first deploy, replace them with LunoraDO in
new_sqlite_classes, so the migration creates only the merged class.
lunora verify reports any migration or binding that still names a per-role
class.
The merge does not move data, in either direction. A ShardDO, SchedulerDO
or ShardRegistryDO namespace that was ever deployed keeps its data in that
class, so leave the merge off for an app that is already live. Once a merged app
is deployed, its data lives in LunoraDO, and turning the merge off again would
leave it behind — so lunora verify refuses that too.
A hand-written worker entry merges the same way:
import type { DurableObjectNamespaceLike } from "@lunora/scheduler";
import type { ShardNamespaceLike } from "@lunora/runtime";
import { defineApp } from "./lunora/_generated/app";
import { AdminRevocationDO } from "./lunora/_generated/adminRevocations";
import { mergeDurableObjects, roleNamespace } from "./lunora/_generated/durableObjects";
import { SchedulerDO } from "./lunora/_generated/scheduler";
import { ShardRegistryDO } from "./lunora/_generated/shardRegistry";
// One binding serves every role, so it carries the scheduler's namespace shape too.
interface Env {
SHARD: DurableObjectNamespaceLike & ShardNamespaceLike;
}
const app = defineApp<Env>()
.shard((env) => env.SHARD)
.adminRevocations((env) => roleNamespace(env.SHARD, "adminRevocations"))
.scheduler({ namespace: (env) => roleNamespace(env.SHARD, "scheduler") })
.shardRegistry((env) => roleNamespace(env.SHARD, "shardRegistry"))
.build();
export const LunoraDO = mergeDurableObjects({
shard: app.ShardDO,
adminRevocations: AdminRevocationDO,
scheduler: SchedulerDO,
shardRegistry: ShardRegistryDO,
});
export default app;Worker size
Cloudflare caps a Worker at
64 MiB uncompressed,
the same on Workers Free and Workers Paid. There is no compressed size limit:
only the uncompressed bundle counts, and the gzip figure wrangler deploy prints
is for reference. The limit is enforced at upload, so an over-budget bundle is a
rejected deploy rather than a slow one.
lunora build weighs what it wrote:
pnpm lunora build
# … bundle: 1684.9 KiB raw across 1 file(s) — 2.6% of Cloudflare's 64 MiB uncompressed
# Worker size limit (412.9 KiB gzipped, for reference; there is no compressed limit)
pnpm lunora build --format json | jq .data.bundle
# { "files": 1, "gzipBytes": 422840, "rawBytes": 1725313 }Only the uploaded files are counted: the sourcemap and the esbuild metafile
sitting in the same out-dir are not part of the script, and counting them would
inflate the number. Compare rawBytes against the 64 MiB limit; a bundle
over it is reported as a warning. gzipBytes matches the gzip: figure in
wrangler's Total Upload: … / gzip: … line and is useful for tracking what
crosses the wire, but Cloudflare does not limit it.
A starter app is small next to that limit, so most projects have a lot of room. A large bundle can also add to startup time, so if yours is growing:
- Drop add-ons you no longer import. Every
@lunora/*add-on your Worker entry reaches is bundled, whether or not a request ever uses it. - Check for a dev-only import reaching the Worker entry. A seed script, a
test helper, or a Node-only utility imported from
lunora/pulls its whole dependency tree into the deployed bundle. - Look at what is actually heavy.
lunora analyzebundles the Worker and prints the largest modules, which is usually enough to name the culprit. - Studio's documents are not in it when wrangler bundles the Worker: they ship as static assets, which do not count toward the limit (see Studio's documents).
Size is not the only upload check. A Worker whose global scope takes more than 1 second to evaluate is rejected with error 10021 however small it is; see Worker startup CPU limit.
Streaming logs
Tail a deployed Worker's live logs with:
pnpm lunora logs # pretty-printed live tail
pnpm lunora logs --format json # one JSON object per line (pipe to jq)
pnpm lunora logs --status error # only failed invocations
pnpm lunora logs --search "userId" # substring filter on log messagesThis wraps wrangler tail, so it needs a deployed Worker and your wrangler
config; pass a Worker name as the first argument to override the configured
one, and --env <name> to target an environment.
For durable, off-Cloudflare log sinks (Datadog, an HTTP endpoint, R2), forward
tail events to a consumer Worker via tail_consumers in wrangler.jsonc:
{
// ...
"tail_consumers": [{ "service": "log-forwarder" }],
}Each entry names a Worker that receives this Worker's logs, exceptions, and
fetch metadata. @lunora/config exports a withTailConsumer(config, consumer)
helper that appends an entry idempotently (deduped by service + environment),
and the wrangler validator flags any tail_consumers entry missing its
service.
Logpush
To ship logs to a retention or security information and event management (SIEM) sink (R2, HTTP, Splunk, Datadog, S3) without a consumer Worker, enable Cloudflare Logpush with a single flag:
{
// ...
"logpush": true,
}Lunora validates that logpush is a boolean (a typo like "logPush" would
otherwise be silently dropped by wrangler), but the sink itself is a Logpush
job created in the Cloudflare dashboard or via the API, and Lunora does not
manage its lifecycle. The Studio surfaces both halves: its Logs → Log drains
panel renders the { "logpush": true } snippet and deep-links to the Cloudflare
observability dashboard where you create the job.
Platform configuration
A few Cloudflare platform features are pure wrangler.jsonc config. There is
no Lunora adapter to import; you declare the block and Lunora's
wrangler-validator shape-checks it, so a typo is a build-time error instead of
a value wrangler silently drops. You always provision the resource itself
(dashboard or wrangler); Lunora validates the config, it does not manage the
lifecycle.
Smart Placement
Smart Placement lets Cloudflare run your Worker close to the services it calls, such as a regional database, instead of close to the user. Opt in with:
{
// ...
"placement": { "mode": "smart" },
}"smart" opts into Smart Placement, "targeted" pins the Worker to a region, host
or hostname, and "off" disables placement for a Worker that inherits an account
default. The validator rejects any other value (a typo like "fast") and a
non-object placement.
mTLS client certificates
To present a client certificate when your Worker calls a mutually-authenticated
upstream, upload the cert (wrangler mtls-certificate upload) and bind it:
{
// ...
"mtls_certificates": [{ "binding": "MY_CERT", "certificate_id": "<from-upload>" }],
}Each entry must name a non-empty binding and a non-empty certificate_id; the
validator flags either when missing.
Workers for Platforms
If you build a multi-tenant platform that deploys user Workers into a dispatch namespace, bind the namespace:
{
// ...
"dispatch_namespaces": [{ "binding": "DISPATCHER", "namespace": "tenants" }],
}Both binding and namespace are required on each entry.
Media, Stream, Workers VPC, and Artifacts
Lunora has no ctx.* surface for these bindings. Read them off env in your own
code. The validator checks their shape, and lunora build --emit-bindings
lists them:
{
// ...
"media": { "binding": "MEDIA" },
"stream": { "binding": "STREAM" },
"vpc_services": [{ "binding": "PRIVATE_API", "service_id": "<service-id>" }],
"vpc_networks": [{ "binding": "MESH", "network_id": "cf1:network" }],
"artifacts": [{ "binding": "ARTIFACTS", "namespace": "default" }],
}A vpc_networks entry needs exactly one of tunnel_id (a Cloudflare Tunnel)
or network_id ("cf1:network" for Cloudflare Mesh). A vpc_services entry
needs a service_id, and an artifacts entry needs a namespace.
Required secrets
secrets.required declares the secret names your Worker needs:
{
// ...
"secrets": { "required": ["API_KEY", "LUNORA_ADMIN_TOKEN"] },
}Once this list exists, wrangler dev loads only the listed keys from
.dev.vars, and wrangler deploy fails while one of them is unset. So when the
list leaves out a secret that one of your Lunora packages needs (for example
LUNORA_ADMIN_TOKEN or AUTH_SECRET), the dev server warns and names it.
Static assets
Lunora deploys as a single Worker, so the conventional way to serve your Vite client build is Workers Static Assets. Cloudflare serves the files for free and only invokes the Worker on a miss, so the Lunora SSR/API fetch handler still runs underneath:
{
// ...
"assets": { "directory": "./dist/client", "binding": "ASSETS" },
}The validator requires a non-empty directory (pointing at the built client
output), a non-empty binding when one is set, an html_handling / not_found_handling value
wrangler accepts, and a run_worker_first that is a boolean or a list wrangler
accepts: path rules starting with / or !/, at least one of them /, at most
100 rules (duplicates included) of 100 characters, none repeated, and none
already covered by another rule ending in *.
Lunora does not auto-inject this block for your client build; the output
directory is framework-adapter-specific, so you declare it. (A Worker with no
assets block of its own gets one for Studio's documents,
which serves nothing publicly.)
Once the block exists, Lunora adds one key to it. Cloudflare answers from the
assets directory before the Worker whenever a file matches, so a request meant
for the Worker could get a static file instead. So the dev server and lunora deploy write run_worker_first (for the top-level block and for each
env.<name>.assets block) with every path the Worker serves that they can see
(a single-page app gets the reverse list):
- Lunora's reserved paths,
/_lunora/*and/__lunora/*; - each
httpRoutepath underlunora/; - when the app imports
@lunora/auth: its base path (a string-literalbasePathpassed tocreateAuth, or a literalauthBasePathWorker option, else the default/api/auth), and the OAuth discovery documents under/.well-known/oauth-protected-resourceand/.well-known/oauth-authorization-server.
{
"assets": {
"directory": "./dist/client",
"run_worker_first": ["/_lunora/*", "/__lunora/*", "/api/auth", "/api/auth/*", "/api/todos/*"],
},
}A rule cannot hold a route parameter, so each parameter becomes a * where it
stands: /api/todos/:id becomes /api/todos/*, /users/:id/avatar.png becomes
/users/*/avatar.png (so the SPA keeps /users/42), and /files/* becomes
/files plus /files/*. A * in a rule matches across / too, so a rule also
takes deeper paths in the parameter's place (/api/todos/1/x,
/users/a/b/avatar.png), which the Worker answers with its 404. A route whose first segment is a parameter
(/:tenant/api), or the site root /, would send every path to the Worker and is
reported instead. Rules another rule covers are dropped, and the list stays
within Cloudflare's limits (100 rules of at most 100 characters); anything over
is reported.
Lunora records the list it wrote under lunora.runWorkerFirst in
package.json, and rewrites it when your routes change. It also takes over a
list an earlier version wrote (the reserved pair, or the old rspack-react
template's ["/_lunora/*"]). When the files under lunora/ cannot be parsed,
the list is left as it is until they can. A run_worker_first
you wrote, or edited after Lunora wrote it, is never changed. If it leaves out
one of the paths above, or a !/… rule takes part of one back, Lunora warns and
names it. Two kinds of route are invisible at config time, so add them yourself:
an auth basePath that is not a string literal, and routes you add to a Hono
httpRouter() directly rather than with httpRoute.
Single-page apps
With not_found_handling: "single-page-application", a list that names only
the Worker's routes is not enough. Once run_worker_first is a list, Cloudflare
answers every request no rule names with index.html and a 200, a fetch or
a webhook POST included: the asset router keeps the SPA fallback whenever
static routing is configured, not only for browser navigations. So a Worker path
Lunora cannot see, such as an auth basePath that is not a string literal or a
route on a Hono httpRouter(), would never reach the Worker.
When the block also sets a binding, Lunora writes the reverse list: the Worker
first for every path, except the static output it can name. That means the
hashed directories bundlers write (assets/, static/, _astro/) and each
top-level entry of public/. An exemption that would take a Worker route back
is left out.
{
"assets": {
"binding": "ASSETS",
"directory": "./dist",
"not_found_handling": "single-page-application",
"run_worker_first": ["/*", "!/_astro/*", "!/assets/*", "!/favicon.ico", "!/static/*"],
},
}The generated Worker then answers what no route serves from that binding:
- a static file the list did not exempt is served as is;
- a
GETorHEADpage navigation (Sec-Fetch-Mode: navigate, or anAcceptthat namestext/html) gets the app shell, so client-side routes deep-link; - any other request keeps the Worker's 404, so a
fetchto a mistyped API path never getsindex.html.
Only a request no route matched falls back. A 404 or 403 that one of your
handlers returns stays as it is, and a POST, PUT, PATCH or DELETE that
misses keeps its 404. That holds for a not-found handler you set on an
httpRouter() with app.notFound(…): it still answers every miss that is not a
page load. A router that is not built by httpRouter() (a plain new Hono())
never reports a miss, so its deep links keep the 404.
Files served this way go through the Worker. Cloudflare applies your _headers
rules to responses from the binding too, and the Worker then adds each of its
security headers the response does not already carry. A value your _headers
sets wins, but a rule that only detaches a header (! X-Frame-Options) is
undone on these responses, since the Worker adds the default back. Set the value
you want instead, or change it in security.headers.
Without a binding, the Worker cannot reach the shell, so Lunora keeps the list
of routes it can see and warns: add "binding": "ASSETS" to the block. The
generated defineApp wires the binding for you; a worker built with
createWorker directly passes it as the spaAssets option.
Because an asset hit never runs the Worker, it also skips the Worker's security
headers. The production build writes them into the assets' _headers file
instead (from the Vite, Rsbuild, Nuxt or Astro integration), in a block it
manages beside your own rules. See Static
assets on the security page.
The same block makes Vite's content-hashed output cacheable. Cloudflare's
default for an asset is Cache-Control: public, max-age=0, must-revalidate, so
a browser revalidates every chunk on every navigation. Every file Vite writes
into build.assetsDir has a content hash in its name, so the block gives that
directory a year-long immutable policy:
/assets/*
Cache-Control: public, max-age=31536000, immutableThe rule is left out when it could cache something that is not a hashed file:
- your
public/has a folder with the same name, which Vite copies in unhashed; - an output file name (
entryFileNames,chunkFileNames,assetFileNames) is a function, or a pattern without[hash]; build.assetsDiris empty;- no
wrangler.jsonc/wrangler.jsonwas found, or it does not parse, sonot_found_handling(below) is unknown; assets.not_found_handlingis"single-page-application"or"404-page"._headersmatches the request path, so after a deploy removes a chunk, a request for it would getindex.htmlor404.htmlwith the immutable policy, and the browser would keep that page for a year. With"none"(or the key unset), a miss goes to the Worker, and_headersnever touches a Worker response.
It is also left out when one of your own _headers rules sets Cache-Control
on a path that reaches that directory (/*, /assets/*, /:dir/*, …). A
Cache-Control rule for another path, such as /img/*, does not affect it.
LUNORA_SECURITY_HEADERS=off does not affect it either.
Studio's documents
Studio's API tab and Architecture view read three generated documents: the
OpenAPI and OpenRPC specs and the architecture manifest. They grow with the app
(hundreds of KiB in a large one) and only the admin routes
/_lunora/admin/openapi, /openrpc and /architecture read them, so the Worker
never loads one before that route's first request. Where they live depends on
how the Worker is built:
| Build | Where the documents live |
|---|---|
wrangler bundles the Worker (no @lunora/vite / @lunora/rspack, no framework), Cloudflare target, no assets block of your own, entry composed with the generated defineApp | Workers Static Assets, outside the Worker script |
an entry that calls createWorker itself | wherever that entry loads them from (usually import() of lunora/_generated/openapi) |
| Vite or Rsbuild | their own chunks of the Worker, loaded with import() |
a project with its own assets block | in the Worker bundle, loaded with import() (your assets directory is your client build's output) |
--target node / celld | in the Worker bundle, loaded with import() (no Workers Static Assets) |
In the first case codegen writes each document to
.lunora/studio-assets/_lunora/studio/<name>.json, and lunora codegen, the
dev server and lunora deploy add this block to wrangler.jsonc:
{
"assets": { "binding": "ASSETS", "directory": ".lunora/studio-assets", "run_worker_first": true },
}run_worker_first: true sends every request to the Worker first, exactly as
with no assets block, so the files are reachable only through the ASSETS
binding. The Worker answers a direct request for /_lunora/studio/* with a 404,
an encoded spelling of that path gets a redirect to it, and the admin route
reads the file through the binding after checking the admin token. Its response
carries Cache-Control: no-store. A deploy replaces the files, and each isolate
reads a document at most once.
The block is removed again when the project moves to a bundler plugin or a
framework. Lunora recognises it by its exact shape, so a block you edit is left
alone, and codegen then deletes the documents it wrote there, since your edited
block may serve that directory before the Worker checks the admin token. Run
lunora build or lunora deploy (or lunora codegen before a plain wrangler deploy): wrangler refuses an assets.directory that does not exist.
Non-goals
A couple of Cloudflare products are deliberately not wired into Lunora:
- Cloudflare Pages. The Lunora Worker is the deploy unit; there is no second Pages artifact. Serve your client build from the same Worker with the Static assets block above instead.
- Pub/Sub (MQTT, Message Queuing Telemetry Transport). Realtime fan-out is handled by Durable-Object-hibernated WebSocket subscriptions (see Real-time), which need no external broker. Cloudflare Pub/Sub, an MQTT broker, never shipped a Worker binding and no longer has a page in Cloudflare's docs; the only thing it would add is native-MQTT device ingest, a narrow case.