◉ANTIGRAVITY LABJP
Articles/App Development
▣ App Development/2026-03-10Intermediate

Cloudflare Workers × Antigravity Deployment Notes: OpenNext, Secrets, and CI/CD

How I put a Next.js app on Cloudflare Workers with the OpenNext adapter, split between what I let the Antigravity agent write and what I check myself: wrangler config, secrets, GitHub Actions, and custom domains.

Cloudflare Workers8deployment7Next.js7edgeWrangler

The morning the deploy was green and the page was yesterday's

The first time I put a Next.js site on Workers, wrangler deploy finished green. No errors in the log. But when I opened the site in the browser, it was still showing the previous day's page. The cause was a config line pointing at an old build output directory. That morning I learned that a successful deploy command and the right content being served are two different things.

Here is what I'd like to say up front: letting the agent draft the config files is fine. What I read line by line myself is where the build output points, which secrets exist and who can see them, and which domain is routed to the Worker.

What follows is the path I take with an Antigravity agent, from a Next.js project to a live Worker through OpenNext. If you have a Cloudflare account and Node.js on your machine, you can follow along.

Scaffolding to the agent, destinations to me. Three lines decide where traffic goes, and I read those aloud every time.

What actually changes on Workers

Workers runs your code on Cloudflare's network, close to the user, billed by usage. For a small site whose traffic I can't predict, not having a fixed monthly cost is a relief.

The catch is that it isn't Node.js. The nodejs_compat flag covers many standard modules, but libraries that assume they can write to the filesystem won't run. Before migrating, I check whether my dependencies work on Workers at all. That's the first inventory.

I'm leaving out figures like location counts or latency percentages. They shift with plans and over time, so please check Cloudflare's current documentation for them.

Setting up the project

For a new project, the official template is the safest start.

npm create cloudflare@latest my-app
cd my-app
npx wrangler login

wrangler login opens a browser to authenticate your account. You'll still see wrangler generate in older write-ups, but it is no longer the recommended path. When an agent proposes an outdated step, I compare it against the official docs and swap it out.

To move an existing Next.js project over, add the adapter:

npm install @opennextjs/cloudflare@latest
npm install -D wrangler@latest

Configuring the OpenNext adapter

Next.js runs on Workers through OpenNext's Cloudflare adapter. This is what I asked the agent:

Add @opennextjs/cloudflare to this Next.js project.
Create open-next.config.ts and wrangler.toml, and add
preview and deploy scripts to package.json.
Show changes as a diff. Do not run the deploy.

The last sentence matters most. The agent writes the config; I press the deploy button myself.

I start open-next.config.ts as small as possible:

// open-next.config.ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare";
 
export default defineCloudflareConfig({});

Adding a cache backend (R2 or KV) can wait until the basics work. If you add everything at once, you can't tell which piece broke.

My scripts look like this:

{
  "scripts": {
    "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
    "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy"
  }
}

A minimal wrangler.toml, and the three lines I check

When the agent hands me a wrangler.toml, I first see whether it resembles this:

name = "my-next-app"
main = ".open-next/worker.js"
compatibility_date = "2026-03-01"
compatibility_flags = ["nodejs_compat"]
 
[assets]
directory = ".open-next/assets"
binding = "ASSETS"

The stale page that morning came from main and the directory under [assets]. Do they match where the build actually writes its output? Those are the lines I read before every deploy.

compatibility_date pins runtime behavior to that date. Raising it enables newer behavior; leaving it keeps the old. It doesn't silently track the latest. When I do bump it, I check a preview first.

Older tutorials use type = "service-worker" or a top-level env = "production". Those don't belong in a current setup, so I check that no such leftovers slipped in.

When you connect D1 or KV

If your app stores data, add bindings:

[[d1_databases]]
binding = "DB"
database_name = "production-db"
database_id = "(the ID shown in your dashboard)"
 
[[kv_namespaces]]
binding = "KV_CACHE"
id = "(the ID shown in your dashboard)"

Never let the agent guess these IDs. It will sometimes write a confident ID that doesn't exist. I copy them from the creation command's output or from the dashboard.

Secrets live in neither code nor Git

API keys and connection strings go in through wrangler secret:

npx wrangler secret put API_KEY

You type the value interactively and it's stored encrypted on Cloudflare's side. For local development, use a .dev.vars file and add it to .gitignore.

# .dev.vars (never commit)
API_KEY=dev-only-value

Once, a throwaway key ended up in a comment inside an agent-written config, and I only noticed it in the staged diff, just before committing. My stomach dropped. Since then I search git diff --staged for key-like strings before every commit, and I put that step in the agent's instructions too.

In code, read secrets from the env object:

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (!env.API_KEY) {
      return new Response("Server misconfigured", { status: 500 });
    }
    return new Response("ok");
  },
};
 
interface Env {
  API_KEY: string;
}

I never print the value itself into a response or a log, even while debugging.

Separate environments, and stop at staging

If you ship production and staging from the same code, give each its own settings:

[env.staging]
name = "my-next-app-staging"
vars = { API_ENDPOINT = "https://staging.example.com" }
 
[env.production]
name = "my-next-app"
vars = { API_ENDPOINT = "https://api.example.com" }
npx wrangler deploy --env staging
npx wrangler deploy --env production

Staging always goes first. I open both a page and an API route there before moving on.

Automating with GitHub Actions

Manual deploys cause the most accidents on tired nights. So pushes to main deploy automatically:

# .github/workflows/deploy.yml
name: Deploy
 
on:
  push:
    branches: [main]
 
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm test
      - run: npx opennextjs-cloudflare build
      - run: npx opennextjs-cloudflare deploy
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

I create the API token with only the permissions Workers deployment needs. I'd rather not leave an account-wide key in CI.

I also end the pipeline with a smoke check:

      - name: Smoke check
        run: |
          code=$(curl -s -o /dev/null -w "%{http_code}" https://example.com/)
          test "$code" = "200"

A status code alone won't catch the "green but stale" morning. If you want to go further, embed a per-build version string in the page and verify after deploy that it matches what you just built.

Connecting a custom domain

If Cloudflare manages your DNS, adding the custom domain from the Workers settings in the dashboard is the most reliable route. In wrangler.toml it looks like this:

routes = [
  { pattern = "app.example.com", custom_domain = true }
]

With custom_domain = true, the DNS record and certificate are provisioned for you. You can create a CNAME by hand, but mismatches creep in, so I avoid that.

Wildcard routes can send more traffic to the Worker than you intended. I start with one hostname and widen only after it works.

Revisiting caching and bundle size

After it works, I measure before I tune.

Static assets are served efficiently outside your Worker thanks to [assets]. For dynamic responses you want to cache, use the Cache API:

const cache = caches.default;
const cacheKey = new Request(request.url, { method: "GET" });
 
let response = await cache.match(cacheKey);
if (!response) {
  response = await fetch(upstreamUrl);
  response = new Response(response.body, response);
  response.headers.set("Cache-Control", "public, max-age=300");
  await cache.put(cacheKey, response.clone());
}
return response;

What matters here is choosing the expiry on purpose. Keeping something for a day that only needed five minutes means updates never show up, and you stare at the screen wondering why.

The N+1 pattern with D1 is another classic trap: don't run queries inside a loop; batch them with a JOIN or an IN clause. For bundle size, look at the output of wrangler deploy --dry-run --outdir dist and remove unneeded dependencies one at a time. Compression is handled by Cloudflare automatically, so there's no need to hand-write gzip in your Worker.

Your next step

From scaffold to production, the agent gets you there in surprisingly few steps. The time is better spent on checking afterwards.

Before your next deploy, try reading main, the [assets] directory, and routes in wrangler.toml out loud. I start there too. Combined with a habit of checking the page's build version after deploy, I think the "green but stale" morning gets much rarer.

Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

▣ App Dev2026-10-18
Before Letting an Agent Touch My Config, I Found That .env* Doesn't Cover .dev.vars, and Wrote a Preflight Script
Auditing my own Cloudflare Workers repo showed that the .env* line in .gitignore never protected .dev.vars. Here is the full Python script that asks git itself where secrets can leak before an agent opens the repo.
▣ App Dev2026-05-01
Deploying Apps with Antigravity to Railway
A hands-on guide to deploying from Antigravity to Railway. Covers when Cloudflare Workers and Vercel fall short, and how Railway fills that gap for long-running tasks and persistent connections.
▣ App Dev2026-04-26
Antigravity × Cloudflare Edge SaaS Architecture Guide: Production Patterns with D1, Workers, R2, and Workers AI
A complete production guide for building edge SaaS with Antigravity + Cloudflare D1, Workers, R2, and Workers AI. Covers real pitfalls including N+1 queries, CPU limits, and cost management.