Deploy AIRouter to Cloudflare Pages
AIRouter runs entirely on Cloudflare Pages — there are no separate Workers. The Pages Functions under /api/* handle every server-side concern (auth, routing, admin, internal). Lightbase is the only persistent store. The free Cloudflare Pages tier is sufficient because every tenant API request hits the in-memory isolate caches; the only Lightbase calls happen on cache misses and admin mutations.
Prerequisites
- Node 20+ installed locally (required by Astro 5 and tsx).
- A Cloudflare account with the Pages permission. The free tier is sufficient.
- A Lightbase project at lightbase.pages.dev. Note the project id, base URL, tenant, and a service-account API key.
- A Cloudflare API token with the Pages:Edit permission (for the direct-upload deploy script) and the account id it belongs to.
Walkthrough
- 1
Clone and install
git clone https://github.com/ridwanullahh/AIRouter-Beta.git cd AIRouter-Beta npm install - 2
Configure
.envCopy the example and fill in every value. The deploy script reads from
.envviascripts/_env.ts.cp .env.example .envRequired environment variables (local and production):
Variable Example Description LIGHTBASE_API_KEYlb_sk_...Service-account key for the AIRouter Lightbase project. Used for all server-side Lightbase calls. LIGHTBASE_PROJECT_IDairouter-betaLightbase project id. The seed script and runtime both scope to this project. LIGHTBASE_BASE_URLhttps://lightbase.pages.devLightbase API base URL. Defaults to the public Lightbase instance. LIGHTBASE_TENANTdefaultLightbase tenant slug for the project. Defaults to default.SESSION_SECRET32 random bytes hex Used to sign dashboard session artifacts if local re-validation is needed. ENCRYPTION_KEY32 random bytes hex 32-byte key for envelope encryption of credentials (if Lightbase field-level encryption is not used) and for any client-side cache encryption. CACHE_INVALIDATION_HMAC_KEY32 random bytes hex HMAC-SHA256 key for the /api/internal/invalidateendpoint.PUBLIC_SITE_URLhttps://airouter-beta.pages.devPublic base URL of the deployment. Used in email templates, OAuth redirects, and absolute URLs. CLOUDFLARE_ACCOUNT_IDyour Cloudflare account id Cloudflare account id. Used by scripts/deploy-cloudflare.ts.CLOUDFLARE_PAGES_API_TOKENa Cloudflare API token Cloudflare API token with Pages:Edit permission. Used by the deploy script. CLOUDFLARE_PROJECT_NAMEairouter-betaCloudflare Pages project name. The deploy script will create it if it does not exist. - 3
Seed Lightbase
Run the seed script. It is idempotent: it creates the 14 collections (lowercase snake_case per Lightbase validation), seeds the 40 providers (37 active + 3 excluded), creates the plan definitions in
system_meta, and registers the monthly reset cron. Safe to re-run; existing records are not duplicated.npm run seedExpected output: 14 collections created, 40 providers seeded, 3 plan definitions present, 1 monthly cron created.
- 4
Build
The Astro build produces static assets for the landing, docs, and dashboard pages, plus Pages Functions for every
/api/*route. The output goes todist/.npm run buildThe build runs TypeScript strict-mode typechecking as part of the Astro pipeline. Any typecheck error fails the build. Verify zero errors before proceeding.
- 5
Deploy
The
deployscript runsbuildfirst, then invokesscripts/deploy-cloudflare.ts. The deploy script:- Reads the env vars from
.env. - Verifies the build output directory exists.
- Gets or creates the Cloudflare Pages project (default name
airouter-beta). - Sets production and preview env vars on the Pages project.
- Creates a direct-upload deployment and uploads every file in
dist/. - Polls the deployment status until ready.
- Prints the production URL.
npm run deployIf the direct-upload API is unavailable, the script falls back to printing the instructions for connecting the GitHub repository in the Cloudflare Pages dashboard (build command
npm run build, output directorydist, production branchmain). - Reads the env vars from
- 6
Verify production
curl -i https://airouter-beta.pages.dev/ # Expect HTTP 200 with the landing HTML. curl -i https://airouter-beta.pages.dev/api/internal/health # Expect HTTP 200 with {"ok": true}. curl -i https://airouter-beta.pages.dev/api/v1/providers # Expect HTTP 200 with the public provider catalog (37 active providers).Then walk through the end-to-end flow:
- Sign up at
/auth/signup. - Add an OpenRouter credential at
/app/providers. - Create an API key at
/app/api-keysand copy theair_sk_...secret. - Send a chat completion via
curlusing the secret. - Verify the request appears in
/app/usage.
- Sign up at
- 7
Set up a custom domain (optional)
In the Cloudflare Pages dashboard, open the
airouter-betaproject, go toCustom domains, and add your domain. Cloudflare provisions the SSL certificate and updates DNS automatically when the domain is on the same Cloudflare account. After provisioning, updatePUBLIC_SITE_URLin the Pages production environment to the new domain and redeploy.See the official guide atdevelopers.cloudflare.com/pages/configuration/custom-domains.
- 8
Rotate secrets and lock down (recommended)
- Rotate
SESSION_SECRET,ENCRYPTION_KEY, andCACHE_INVALIDATION_HMAC_KEYafter the first production deploy if any value was used in a non-production environment. - Confirm the Lightbase API key has the minimum scope needed (write to the 14 collections, no admin actions on other projects).
- Enable the per-org IP allow-list via
/app/settingsfor any org with a known IP range. - Verify the audit log at
/app/audit-logrecords each deploy-triggered cache invalidation.
- Rotate
Free-tier sustainability
AIRouter is designed to fit within the Cloudflare Pages free tier without scaling to a paid plan. Three properties make this possible:
- Per-isolate caching. Every tenant API request reads credentials, routing rules, org context, and the API key from in-isolate memory. Cache TTLs are: apiKeyCache 5 min, credentialsCache 5 min, routingRulesCache 60 s, systemSettingsCache 60 s, orgCache 30 s. A typical request makes zero Lightbase calls.
- TTL invalidation. Short TTLs mean a stale cache self-heals within minutes. Admin mutations additionally push an explicit invalidation via
invalidateOrg/invalidateApiKey/invalidateAllfor the local isolate and via the HMAC-signedPOST /api/internal/invalidatefor cross-isolate invalidation. - Zero per-request database calls. The chat completions endpoint, on a cache hit, makes exactly one network call — the upstream provider fetch. Usage recording is fire-and-forget. Lightbase is contacted only on cache miss or admin mutation.
The Pages free tier offers 100 000 invocations per day and unlimited static asset requests. AIRouter's traffic profile fits comfortably within this envelope for the typical small-to-medium org.
Rolling back
Cloudflare Pages retains every production deployment. To roll back, open the Pages dashboard, find the previous deployment in the deployments list, and clickPromote to production. The DNS and CDN update within seconds. Thedist/ artifacts of every prior deploy are kept by Cloudflare for the lifetime of the project.
No separate Cloudflare Workers
AIRouter does not deploy any Cloudflare Workers. All server-side code lives in Pages Functions (Astro's @astrojs/cloudflare adapter produces dist/_worker.jswith the Pages Functions bundle). The deploy script uploads the bundle to the Pages project; Cloudflare runs it on the Pages runtime. This is by design — it keeps the deployment story simple, fits the free tier, and avoids the additional cost and operational overhead of a separate Workers plan.