Cloudflare Pages deployment

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. 1

    Clone and install

    git clone https://github.com/ridwanullahh/AIRouter-Beta.git
    cd AIRouter-Beta
    npm install
  2. 2

    Configure .env

    Copy the example and fill in every value. The deploy script reads from .env via scripts/_env.ts.

    cp .env.example .env

    Required environment variables (local and production):

    VariableExampleDescription
    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 hexUsed to sign dashboard session artifacts if local re-validation is needed.
    ENCRYPTION_KEY32 random bytes hex32-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 hexHMAC-SHA256 key for the /api/internal/invalidate endpoint.
    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 idCloudflare account id. Used by scripts/deploy-cloudflare.ts.
    CLOUDFLARE_PAGES_API_TOKENa Cloudflare API tokenCloudflare 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. 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 seed

    Expected output: 14 collections created, 40 providers seeded, 3 plan definitions present, 1 monthly cron created.

  4. 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 to dist/.

    npm run build

    The build runs TypeScript strict-mode typechecking as part of the Astro pipeline. Any typecheck error fails the build. Verify zero errors before proceeding.

  5. 5

    Deploy

    The deploy script runs build first, then invokesscripts/deploy-cloudflare.ts. The deploy script:

    1. Reads the env vars from .env.
    2. Verifies the build output directory exists.
    3. Gets or creates the Cloudflare Pages project (default name airouter-beta).
    4. Sets production and preview env vars on the Pages project.
    5. Creates a direct-upload deployment and uploads every file in dist/.
    6. Polls the deployment status until ready.
    7. Prints the production URL.
    npm run deploy

    If 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 directory dist, production branch main).

  6. 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:

    1. Sign up at /auth/signup.
    2. Add an OpenRouter credential at /app/providers.
    3. Create an API key at /app/api-keys and copy the air_sk_... secret.
    4. Send a chat completion via curl using the secret.
    5. Verify the request appears in /app/usage.
  7. 7

    Set up a custom domain (optional)

    In the Cloudflare Pages dashboard, open the airouter-beta project, 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, update PUBLIC_SITE_URL in the Pages production environment to the new domain and redeploy.

    See the official guide atdevelopers.cloudflare.com/pages/configuration/custom-domains.

  8. 8

    Rotate secrets and lock down (recommended)

    • Rotate SESSION_SECRET, ENCRYPTION_KEY, and CACHE_INVALIDATION_HMAC_KEY after 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/settings for any org with a known IP range.
    • Verify the audit log at /app/audit-log records each deploy-triggered cache invalidation.

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:

  1. 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.
  2. TTL invalidation. Short TTLs mean a stale cache self-heals within minutes. Admin mutations additionally push an explicit invalidation viainvalidateOrg / invalidateApiKey / invalidateAllfor the local isolate and via the HMAC-signedPOST /api/internal/invalidate for cross-isolate invalidation.
  3. 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.