Skip to content

Cloudflare Workers and GitHub Integration

Cloudflare Workers is Serverless code running on edge nodes. Although you can write code directly in the web console, for production environment projects, using local development + GitHub hosting + Actions automatic deployment is the best practice.

Serverless

Prerequisites

  1. GitHub account with your Workers project repository.
  2. Cloudflare account.
  3. Project root directory contains wrangler.toml configuration file.

Get API Token

To allow GitHub Action permission to publish code to your Cloudflare account, you need to create an API Token.

  1. Log in to Cloudflare Dashboard.
  2. Click the avatar in the upper right corner -> My Profile -> API Tokens.
  3. Click Create Token.
  4. Use the template Edit Cloudflare Workers.
  5. Complete creation, copy this Token (displayed only once).

Configure GitHub Secrets

  1. Enter your GitHub repository.
  2. Click Settings -> Secrets and variables -> Actions.
  3. Click New repository secret.
    • Name: CLOUDFLARE_API_TOKEN
    • Secret: (Paste the Token you just copied)
  4. (Optional) If you need Account ID, you can also add a CLOUDFLARE_ACCOUNT_ID.

Write Workflow File

Create .github/workflows/deploy.yml in your repository:

yaml
name: Deploy Worker

on:
  push:
    branches:
      - main  # Monitor commits to main branch

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      # 1. Checkout code
      - uses: actions/checkout@v4

      # 2. Deploy to Cloudflare Workers
      - name: Deploy with Wrangler
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          # accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} # If account_id is not in wrangler.toml, specify it here

How It Works?

  1. When you finish local development and run git push origin main.
  2. GitHub detects the push event and starts the Action.
  3. cloudflare/wrangler-action will automatically install the latest wrangler CLI tool.
  4. It will read the wrangler.toml configuration in your repository.
  5. Use CLOUDFLARE_API_TOKEN for authentication to upload and publish the latest code to Cloudflare global network.

Common wrangler.toml Configuration

Ensure your project has this file, otherwise Action won't know where to send it.

toml
name = "my-worker-project"
main = "src/index.js" # Entry file
compatibility_date = "2024-01-01"

# If using KV storage
# [[kv_namespaces]]
# binding = "MY_KV"
# id = "xxxxxxxxxxxx"

All resources are from the open-source community. Disclaimer