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.
ServerlessPrerequisites
- GitHub account with your Workers project repository.
- Cloudflare account.
- Project root directory contains
wrangler.tomlconfiguration file.
Get API Token
To allow GitHub Action permission to publish code to your Cloudflare account, you need to create an API Token.
- Log in to Cloudflare Dashboard.
- Click the avatar in the upper right corner -> My Profile -> API Tokens.
- Click Create Token.
- Use the template Edit Cloudflare Workers.
- Complete creation, copy this Token (displayed only once).
Configure GitHub Secrets
- Enter your GitHub repository.
- Click Settings -> Secrets and variables -> Actions.
- Click New repository secret.
- Name:
CLOUDFLARE_API_TOKEN - Secret: (Paste the Token you just copied)
- Name:
- (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 hereHow It Works?
- When you finish local development and run
git push origin main. - GitHub detects the push event and starts the Action.
cloudflare/wrangler-actionwill automatically install the latestwranglerCLI tool.- It will read the
wrangler.tomlconfiguration in your repository. - Use
CLOUDFLARE_API_TOKENfor 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"