Skip to main content

CI/CD and automation · Intermediate · 18 min

Deploy a Cloudflare Worker from GitHub Actions

By Padding · Updated 18 Nov 2026
Node.js 26.13 · Wrangler 4.168.0 · cloudflare/wrangler-action v4.1.3 · actionlint 1.7.12

You will have a GitHub Actions workflow that tests a Cloudflare Worker on every push and pull request, deploys it from main only with a scoped API token held in a production environment, uploads its secrets with wrangler secret bulk and rolls it back on request.

On this page

Running wrangler deploy from your laptop works until two people do it from two different branches, or until someone deploys code whose tests they never ran. Moving the deploy into GitHub Actions fixes both: the code that reaches Cloudflare is always what is on main, and it only gets there after the tests pass on a clean machine.

In this tutorial you build a small Worker with a Vitest suite, then write one workflow with four jobs. test runs on every push and pull request. deploy runs only on a push to main, after test passes. Two manual jobs, started from the Actions tab or the GitHub CLI, upload the Worker's secrets with wrangler secret bulk and roll back to an earlier version. The Cloudflare credential is an API token that can only manage Workers on one account, kept in a GitHub environment so that only those jobs can read it.

Once the workflow is pushed, the installs and the deploy run on GitHub's machines, not yours. If you pay for mobile data by the megabyte, the only traffic from your side after the first npm install is a small git push.

Commands run on your computer, in ~/worker-ci-demo, unless they say otherwise.

Step 1 · Build a small Worker with tests

Create the project and a Git repository with main as its first branch:

Bash
mkdir -p ~/worker-ci-demo
cd ~/worker-ci-demo
git init -b main
npm init -y
npm pkg set type=module scripts.test="vitest run"
npm install --save-dev --save-exact wrangler@4.168.0 vitest@4.1.12 @cloudflare/vitest-plugin@1.9.2

npm install also writes package-lock.json. Commit it: the workflow installs with npm ci, which refuses to run without a lock file and installs exactly the versions in it.

Keep local state and secret files out of Git from the start:

Bash
cat > .gitignore <<'EOF'
node_modules/
.wrangler/
.dev.vars*
.env*
EOF

The Worker's configuration has two plain settings. RELEASE is a label you will change later, so you can see which version is live:

Bash
cat > wrangler.jsonc <<'EOF'
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "ci-demo-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-20",
  "vars": {
    "GREETING": "Hello from GitHub Actions",
    "RELEASE": "v1"
  }
}
EOF

The Worker answers / with the greeting and the release, and /api/ping with JSON, but only for a caller who sends the API_TOKEN secret as a bearer token:

Bash
mkdir -p src
cat > src/index.ts <<'EOF'
interface Env {
  GREETING: string;
  RELEASE: string;
  API_TOKEN?: string;
}

// Constant-time comparison, so response timing does not leak the token.
function hasToken(request: Request, token: string): boolean {
  const encoder = new TextEncoder();
  const given = encoder.encode(request.headers.get("Authorization") ?? "");
  const expected = encoder.encode(`Bearer ${token}`);
  if (given.byteLength !== expected.byteLength) return false;
  return crypto.subtle.timingSafeEqual(given, expected);
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/") {
      return new Response(`${env.GREETING} (${env.RELEASE})\n`, {
        headers: { "Content-Type": "text/plain; charset=utf-8" },
      });
    }

    if (url.pathname === "/api/ping") {
      if (!env.API_TOKEN) return Response.json({ error: "server not configured" }, { status: 500 });
      if (!hasToken(request, env.API_TOKEN)) return Response.json({ error: "unauthorised" }, { status: 401 });
      return Response.json({ ok: true, release: env.RELEASE });
    }

    return Response.json({ error: "not found" }, { status: 404 });
  },
};
EOF

The build and test tutorial explains each of these pieces in more detail. Now the tests. Cloudflare's Vitest plugin runs them inside workerd, the Workers runtime, with the settings from wrangler.jsonc and a fixed token for the protected route:

Bash
cat > vitest.config.ts <<'EOF'
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [
    cloudflareTest({
      wrangler: { configPath: "./wrangler.jsonc" },
      miniflare: { bindings: { API_TOKEN: "test-token" } },
    }),
  ],
});
EOF
mkdir -p test
cat > test/index.test.ts <<'EOF'
import { env } from "cloudflare:workers";
import { describe, expect, it } from "vitest";
import worker from "../src/index";

const call = (path: string, init?: RequestInit) =>
  worker.fetch(new Request(`http://example.com${path}`, init), env as never);

describe("ci-demo-worker", () => {
  it("shows the greeting and release", async () => {
    const response = await call("/");
    expect(await response.text()).toBe("Hello from GitHub Actions (v1)\n");
  });

  it("refuses /api/ping without a token", async () => {
    expect((await call("/api/ping")).status).toBe(401);
  });

  it("refuses /api/ping with the wrong token", async () => {
    const response = await call("/api/ping", { headers: { Authorization: "Bearer nope" } });
    expect(response.status).toBe(401);
  });

  it("answers /api/ping with the right token", async () => {
    const response = await call("/api/ping", { headers: { Authorization: "Bearer test-token" } });
    expect(await response.json()).toEqual({ ok: true, release: "v1" });
  });

  it("returns 404 for unknown paths", async () => {
    expect((await call("/nope")).status).toBe(404);
  });
});
EOF
npm test

Check it worked

Vitest lists five tests under ci-demo-worker and ends with 5 passed. git status shows package-lock.json, src/, test/ and the config files as untracked, and does not list node_modules.

Step 2 · Create an API token that can only deploy Workers

Wrangler in CI signs in with an API token, read from the CLOUDFLARE_API_TOKEN environment variable. Do not use your account's Global API Key for this. That key can do anything your user can do on every account you belong to, and it cannot be narrowed. A token can.

In the Cloudflare dashboard:

  1. Open API Tokens and choose Create Token.
  2. Start from the Edit Cloudflare Workers template.
  3. Under Account Resources, include only the one account the Worker lives in, not all accounts.
  4. Under Zone Resources, include only the one zone (domain) you will route the Worker on, rather than all zones. A Worker served on its workers.dev address does not use a zone.
  5. Leave IP filtering empty: GitHub-hosted runners do not have fixed addresses. You can set an expiry date, and if you do, put a reminder in your calendar to rotate the token before it lapses.
  6. Name the token after its job, such as github-actions-ci-demo-worker, create it, and copy it. Cloudflare shows the value once.

Check that the token works and find your account ID. read -rs takes the token without printing it, so it stays out of your shell history and off the screen:

Bash
read -rs -p "Cloudflare API token: " CLOUDFLARE_API_TOKEN; echo
export CLOUDFLARE_API_TOKEN
npx wrangler whoami
unset CLOUDFLARE_API_TOKEN

Check it worked

wrangler whoami prints something like You are logged in with an API Token, followed by a table with your account's name and its 32-character account ID. Copy the account ID. If it shows an authentication error, the token was copied incompletely or has already been deleted: create a new one.

Step 3 · Put the token in a GitHub production environment

A secret stored at repository level is readable by every job in every workflow. A secret stored in an environment is only handed to jobs that name that environment, and you can restrict which branches may use it. First connect the local project to your GitHub repository, so gh knows which repository you mean. Replace the address with your repository's:

Bash
git remote add origin git@github.com:<your-user>/<your-repo>.git

Then create a production environment. gh fills in {owner}/{repo} from that remote:

Bash
gh api --method PUT "repos/{owner}/{repo}/environments/production"

Store the Cloudflare token as an environment secret. With no --body, gh prompts for the value, so paste it at the prompt:

Bash
gh secret set CLOUDFLARE_API_TOKEN --env production

The account ID is not a secret, so keep it as a variable, which shows in logs and is easier to check. Replace the placeholder with your ID:

Bash
gh variable set CLOUDFLARE_ACCOUNT_ID --env production --body "<your-account-id>"

The Worker itself needs API_TOKEN. Generate a random value, save it in your password manager, then store it as a second environment secret, pasted at the prompt:

Bash
node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))'
gh secret set WORKER_API_TOKEN --env production

GitHub keeps this value and a manual job uploads it to Cloudflare. That makes GitHub the one place you change it, instead of someone running wrangler secret put by hand and nobody knowing which value is live.

To allow only main to deploy, and to require a reviewer before each deploy, set deployment branch rules and required reviewers on the environment as shown in /tutorials/require-approval-before-production-deploys-with-github-environments. The workflow below works with or without them.

Check it worked

gh secret list --env production lists CLOUDFLARE_API_TOKEN and WORKER_API_TOKEN (names and dates only, never values), and gh variable list --env production shows CLOUDFLARE_ACCOUNT_ID with your ID.

Step 4 · Write the workflow

One file holds all four jobs. Write it:

Bash
mkdir -p .github/workflows
cat > .github/workflows/worker.yml <<'EOF'
name: Worker

on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:
    inputs:
      task:
        description: Manual task to run
        type: choice
        options: [rollback, sync-secrets]
        default: rollback
      version_id:
        description: "rollback: version ID to restore (leave empty to list versions)"
        type: string
        required: false
      reason:
        description: "rollback: why you are rolling back"
        type: string
        required: false

permissions:
  contents: read

jobs:
  test:
    if: github.event_name != 'workflow_dispatch'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm test

  deploy:
    needs: test
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment:
      name: production
      url: ${{ steps.deploy.outputs.deployment-url }}
    concurrency:
      group: worker-production
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - id: deploy
        uses: cloudflare/wrangler-action@v4
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
          wranglerVersion: "4.168.0"
          command: deploy

  sync-secrets:
    if: github.event_name == 'workflow_dispatch' && inputs.task == 'sync-secrets'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: production
    concurrency:
      group: worker-production
      cancel-in-progress: false
    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - name: Upload Worker secrets
        shell: bash
        env:
          WORKER_API_TOKEN: ${{ secrets.WORKER_API_TOKEN }}
        run: |
          node -e '
            const token = process.env.WORKER_API_TOKEN;
            if (!token) throw new Error("WORKER_API_TOKEN is empty");
            process.stdout.write(JSON.stringify({ API_TOKEN: token }));
          ' | npx wrangler secret bulk

  rollback:
    if: github.event_name == 'workflow_dispatch' && inputs.task == 'rollback'
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: production
    concurrency:
      group: worker-production
      cancel-in-progress: false
    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - name: List recent versions and deployments
        run: |
          npx wrangler versions list
          npx wrangler deployments list
      - name: Roll back
        if: inputs.version_id != ''
        env:
          VERSION_ID: ${{ inputs.version_id }}
          REASON: ${{ inputs.reason }}
        run: |
          if [[ ! "$VERSION_ID" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]]; then
            echo "version_id must be a version ID from the list above"
            exit 1
          fi
          npx wrangler rollback "$VERSION_ID" --message "${REASON:-no reason given} (by $GITHUB_ACTOR)"
EOF

What each part does:

  • test runs on pushes to main and on every pull request, but not on manual runs. It installs from the lock file and runs the same npm test you ran.
  • deploy needs test, so a failing test stops the deploy. Its if limits it to pushes to main: a pull request runs the tests and nothing else, and pull requests from forks never see the production secrets. environment: production is what gives the job CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID, and url puts the Worker's address on the run page.
  • wrangler-action runs wrangler deploy with the token and account ID you pass in. wranglerVersion matches the version in package.json, so CI and your computer use the same Wrangler.
  • sync-secrets builds the JSON {"API_TOKEN": "..."} from the environment secret and pipes it to wrangler secret bulk, which reads standard input when given no file. The value never touches the runner's disk or the command line, and GitHub masks it in the log. The throw stops the job if the secret is missing, instead of uploading an empty token. That only works because the step sets shell: bash: without it GitHub runs the script with bash -e, where a pipeline's exit status is that of its last command, so a failing node would be ignored and Wrangler would receive empty input. With shell: bash the runner adds -o pipefail, and the failure in node fails the step. Add more keys to the object as your Worker gains secrets.
  • rollback always lists the recent versions first. Given a version_id, it checks that the input looks like a version ID and rolls back to it. --message records why, and also tells Wrangler not to ask for confirmation, which matters on a runner where nobody can answer.
  • Inputs go through env, never straight into the script as ${{ inputs.reason }}. Text pasted into an input would otherwise become part of the shell script.
  • concurrency with the same group on the three production jobs queues them one behind another, so a rollback never runs at the same moment as a deploy.

The two manual jobs are kept apart from the deploy on purpose. Every wrangler secret bulk creates and deploys a new version of the Worker. If the deploy job also uploaded secrets each time, every push would make two versions, and "the previous version" would usually be the same code with different secrets.

Check the file with actionlint 1.7.12 (/tutorials/github-actions-first-workflow shows how to install it), then run what the test job runs:

Bash
actionlint
echo "actionlint exit code: $?"
npm ci
npm test

Check it worked

actionlint prints nothing and the exit code is 0. npm ci reinstalls from the lock file and npm test again reports 5 passed. grep -n 'environment' .github/workflows/worker.yml shows production on the deploy, sync-secrets and rollback jobs and not on test.

Step 5 · Push and watch the first deploy

Commit everything and push to main:

Bash
git add .
git commit -m "Test and deploy the Worker from GitHub Actions"
git push -u origin main
gh run watch

gh run watch asks which run to follow if there is more than one, then shows each job as it runs. test finishes first, then deploy starts. Wrangler's output in the deploy log ends with the Worker's address, in the form https://ci-demo-worker.<your-subdomain>.workers.dev, and the same address appears next to the production environment on the run's summary page.

The first deploy creates the Worker, so it has no API_TOKEN yet and /api/ping answers 500 server not configured, the safe failure the code was written for. Upload the secret with the manual job:

Bash
gh workflow run worker.yml -f task=sync-secrets
gh run watch

Check it worked

Replace the address with yours. The first call prints Hello from GitHub Actions (v1). The second reads the Worker token from a prompt and sends it on standard input, and prints {"ok":true,"release":"v1"}:

Bash
curl -s https://ci-demo-worker.<your-subdomain>.workers.dev/
read -rs -p "Worker token: " TOKEN; echo
printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -s -H @- https://ci-demo-worker.<your-subdomain>.workers.dev/api/ping

Step 6 · See a pull request run tests without deploying

Change the release label on a branch and open a pull request. This rewrites wrangler.jsonc with the new value, so the change is the same on macOS and Linux:

Bash
git switch -c release-v2
cat > wrangler.jsonc <<'EOF'
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "ci-demo-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-20",
  "vars": {
    "GREETING": "Hello from GitHub Actions",
    "RELEASE": "v2"
  }
}
EOF
git commit -am "Release v2"
git push -u origin release-v2
gh pr create --fill

The tests still expect v1, so the test job fails on the pull request. That is the gate doing its job. Update the two expectations in test/index.test.ts from v1 to v2, run npm test locally, commit and push again. The pull request turns green, and deploy shows as skipped because the event is a pull request.

Merge the pull request on GitHub. The push to main runs test and then deploy.

Check it worked

On the pull request's checks, test passed and deploy is listed as skipped. After the merge, curl -s https://ci-demo-worker.<your-subdomain>.workers.dev/ prints Hello from GitHub Actions (v2).

Step 7 · Roll back from the Actions tab

Suppose v2 is broken. Start the rollback job with no version ID to see what you can go back to:

Bash
gh workflow run worker.yml -f task=rollback
gh run watch
gh run view --log

The log of the List recent versions and deployments step shows the 10 most recent versions, each with its version ID, the time it was created and what created it, followed by the recent deployments. Find the version that served v1 after the secret upload (the one created by the secret bulk step, before the v2 deploy) and copy its ID. Then roll back to it, with a reason:

Bash
gh workflow run worker.yml -f task=rollback -f version_id=<version-id> -f reason="v2 breaks ping"
gh run watch

You can start the same job from the Actions tab: choose the Worker workflow, then Run workflow, and fill in the three fields.

A rollback switches the live Worker to the old version at once, on every route. It does not change your repository. Until you undo the change on main, the next push deploys v2 again, so follow the rollback with a revert: open the merged pull request on GitHub, choose Revert, and merge the pull request GitHub opens. That merge runs the pipeline and deploys v1 as a fresh version, and main matches what is live again. Rollbacks also have limits: Cloudflare keeps only recent versions available to roll back to, and it refuses a rollback when a binding the old version needs (a KV namespace or an R2 bucket, for example) has since been removed or changed.

Check it worked

The Roll back step's log ends with Wrangler confirming the rollback, and curl -s https://ci-demo-worker.<your-subdomain>.workers.dev/ prints Hello from GitHub Actions (v1) again. Run the rollback task once more with no version ID: the newest deployment in the list carries your reason and your GitHub username as its message.

Step 8 · Clean up

Delete the Worker when you are done. This removes it and its workers.dev address permanently, so check the name first. Use the API token once more from a prompt:

Bash
read -rs -p "Cloudflare API token: " CLOUDFLARE_API_TOKEN; echo
export CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID="<your-account-id>"
npx wrangler delete --name ci-demo-worker
unset CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID

Then delete the API token in the Cloudflare dashboard (API Tokens, the token's menu, Delete), so nobody can use a copy of it. Remove the environment and its secrets from GitHub, and the local project:

Bash
gh api --method DELETE "repos/{owner}/{repo}/environments/production"
Bash
cd ~
rm -rf ~/worker-ci-demo

Delete or archive the GitHub repository too if you made it only for this tutorial.

Check it worked

The Worker no longer appears in the Cloudflare dashboard's list of Workers, the token is gone from the API Tokens list, gh api "repos/<your-user>/<your-repo>/environments" no longer lists production, and ls ~/worker-ci-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.