| | |

Cloudflare 04 ☁️ Wrangler CLI & Local Development — Running wrangler dev, emulating bindings locally, managing secrets, and deploying from CI/CD

⏱️ Estimated read: 8 min | |

Wrangler is the official CLI tool for the Cloudflare Developer Platform. It is the command-center for everything from creating new projects to managing production deployments. Developing for the edge presents a unique challenge: your code runs in a V8 isolate (a specialized JavaScript runtime), not a standard Node.js environment. To bridge this gap, Wrangler includes a high-fidelity local emulation engine that replicates the Cloudflare global runtime, including bindings (KV, R2, D1), environment variables, and request handling.

Local development is no longer just about running a script; it is about simulating a production-grade distributed system on your laptop. Wrangler allows you to mock databases, inject KV values, and test your code against local versions of your production bindings. Once you are satisfied locally, the same CLI tool handles the packaging, authentication, and deployment to Cloudflare’s global network, ensuring that the “it works on my machine” promise holds true for the edge.

This chapter details the Wrangler CLI workflow. We will explore the nuances of wrangler dev, the configuration of local bindings for different environments, the secure management of production secrets, and the integration of Wrangler into CI/CD pipelines using API tokens.

Key point: Wrangler is the bridge between your local development environment and the Cloudflare edge; it provides a faithful runtime emulation for local testing and a secure, standardized mechanism for deploying code and managing infrastructure across multiple environments.


Why X exists

The runtime disparity problem. Cloudflare Workers run in a non-Node.js, V8 isolate environment. If you test your code only on a local Node server (like express), you will inevitably encounter “it-works-locally-but-fails-in-production” bugs due to API differences (e.g., Request/Response globals vs Node’s http module). Wrangler exists to run your code in a environment that mimics the edge.

The “Binding” complexity. Modern apps rely on KV, R2, D1, and Queues. Testing these without an emulator requires deploying to a dev environment on every save, which is slow and expensive. Wrangler allows you to emulate these bindings locally with SQLite for D1 or JSON files for KV.

The CI/CD credential problem. Deploying to production typically requires long-lived API keys. Managing these securely in an automated pipeline requires careful handling. Wrangler is designed to work with scoped API tokens, allowing for least-privilege access in CI/CD environments.

The configuration drift problem. Managing environment-specific settings—such as different database IDs for dev, staging, and production—can become messy. Wrangler uses the wrangler.jsonc (or toml) file to manage these settings centrally, allowing you to switch environments with a simple CLI flag.

The trade-off. The trade-off is the complexity of the tooling. Wrangler is a powerful tool with many sub-commands and configuration options. Learning to effectively navigate the CLI and configure complex bindings requires a time investment, but it is necessary for maintaining a professional developer workflow at the edge.


a. Emulating Bindings with wrangler dev

The wrangler dev command is the heart of local development. It spins up a local server that runs your Worker code and emulates the bindings defined in your config. When you use a binding (like env.MY_KV), Wrangler intercepts that call and directs it to a local JSON file or a local SQLite database, rather than the real production service.

# Run the local emulator
wrangler dev

This local environment is “hot-reloading.” Any change to your source files or configuration causes the emulator to restart, providing an immediate feedback loop. You can also mock specific data for your bindings by using the --kv or --d1 flags, or by editing local files that the emulator watches.

b. Secret Management

You should never store API keys, database passwords, or private tokens in your source code. Wrangler provides a secure “secrets” store that encrypts your credentials and uploads them to Cloudflare’s production infrastructure.

# Set a secret for your production environment
wrangler secret put API_TOKEN

When you run this command, Wrangler prompts you to enter the value, encrypts it, and pushes it to the Cloudflare API. When your code runs at the edge, the secret is automatically injected into the env object. For local development, Wrangler will allow you to use a .dev.vars file to hold these secrets locally, ensuring you don’t need real production keys to test locally.

c. CI/CD and API Tokens

In a CI/CD pipeline (GitHub Actions, GitLab CI), you cannot interactively log in to Wrangler. Instead, you use a scoped API Token. You create this token in the Cloudflare Dashboard, providing it only the permissions necessary for that specific project.

# CI/CD Command
wrangler deploy --token $CLOUDFLARE_API_TOKEN

The CI/CD environment must also have the CLOUDFLARE_ACCOUNT_ID available. By passing the token as an environment variable or via the --token flag, you allow the pipeline to authenticate as a service account, ensuring that deployments are triggered by the pipeline, not by a human developer.


Complete Example Session

// ============================================
// PART 1: LOCAL CONFIG (wrangler.jsonc)
// ============================================
{
  "name": "my-worker",
  "main": "src/index.ts",
  "kv_namespaces": [
    { "binding": "MY_KV", "id": "local-kv-id" }
  ]
}

// ============================================
// PART 2: LOCAL SECRETS (.dev.vars)
// ============================================
// Do not commit this file!
API_SECRET=super-secret-key-for-dev

// ============================================
// PART 3: LOCAL DEVELOPMENT
// ============================================
// Start emulator
wrangler dev

// ============================================
// PART 4: PRODUCTION SECRETS
// ============================================
// Push to real Cloudflare storage
wrangler secret put API_SECRET

// ============================================
// PART 5: MULTI-ENVIRONMENT CONFIG
// ============================================
// wrangler.jsonc
{
  "env": {
    "staging": {
      "vars": { "DB_NAME": "staging-db" }
    },
    "production": {
      "vars": { "DB_NAME": "prod-db" }
    }
  }
}

// ============================================
// PART 6: DEPLOYING TO ENVIRONMENTS
// ============================================
wrangler deploy --env staging

// ============================================
// PART 7: CI/CD DEPLOYMENT
// ============================================
// GitHub Action steps
// - run: npm install
// - run: npx wrangler deploy
//   env:
//     CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
//     CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}

// ============================================
// PART 8: LOGGING
// ============================================
// Stream real-time logs from the edge
wrangler tail

// ============================================
// PART 9: D1 DATABASE MIGRATIONS
// ============================================
// Apply local migrations to local sqlite
wrangler d1 migrations apply my-db --local

// Apply migrations to production
wrangler d1 migrations apply my-db --remote

The steps above covered setting up the local dev environment, secrets management, multi-environment deployments, and CI/CD integration.


Quick Reference

Wrangler CLI Commands

CommandAction
wrangler devStart local emulator
wrangler deployDeploy to production
wrangler secret putSecurely save secrets
wrangler tailStream real-time logs

Binding Emulation

BindingLocal Store
KVLocal .json file
D1Local sqlite file
R2Local filesystem folder

Environment Variables

VariableSource
.dev.varsUsed by wrangler dev
wrangler.jsoncUsed by wrangler deploy
SecretsInjected at runtime

Best Practices

✅ Do This:

# Add .dev.vars to .gitignore                          // ✅
# Use API Tokens (not Global Keys) for CI/CD           // ✅
# Run `wrangler tail` to debug production issues       // ✅
# Use environments for staging/production separation   // ✅
# Always apply D1 migrations remotely                  // ✅

❌ Don’t Do This:

# Commit secrets to Git                                // ❌
# Use the same database for dev and prod               // ❌
# Deploy without checking `wrangler dev` first         // ❌
# Use Global API keys for CI/CD                        // ❌
# Manually edit remote KV values if possible           // ❌

Common Pitfalls

PitfallWhy It HappensFix
Local vs Prod mismatchNode modules in codeUse standard Web API only
Token expiredCI/CD failureRefresh API token
Secrets missingNot set in productionRun wrangler secret put
Dev logs emptyToo much trafficFilter wrangler tail output
D1 migration errorRemote schema conflictRun migrations in order

Real-World Examples

1. GitHub Actions Pipeline

Automatically deploying to production on merge to main.

2. Local D1 Testing

Testing database schema changes against a local SQLite file.

3. Staging vs Production

Deploying two versions of the app, one with staging- prefix.

4. Remote Tail

Debugging a production 500 error in real-time.

5. Local KV Mocking

Using a static JSON file to mock KV data during development.

6. Secrets Rotation

Updating a database password using wrangler secret put.

7. Multi-Environment

Switching configuration context with --env production.

8. Migrations

Updating D1 database schema with --remote.

9. Service Bindings

Connecting two Workers locally using the emulator.

10. Preview CI

Deploying a preview environment on every Pull Request.


Visual

The Wrangler Development Loop

┌──────────────────────────────────────────────┐
│  LOCAL DEVELOPMENT (Laptop)                  │
│  - wrangler dev                              │
│  - .dev.vars (Secrets)                       │
│  - SQLite (D1) / JSON (KV)                   │
│         │                                    │
│         ▼                                    │
│  PRODUCTION (Cloudflare Edge)                │
│  - wrangler deploy                           │
│  - Cloudflare Secrets (Encrypted)            │
│  - Real D1 / Real KV                         │
└──────────────────────────────────────────────┘

CI/CD Flow

┌──────────────────────────────────────────────┐
│  GITHUB ACTIONS                              │
│  1. Install dependencies                     │
│  2. Run tests                                │
│  3. wrangler deploy --token $CF_TOKEN        │
│         │                                    │
│         ▼                                    │
│  CLOUDFLARE EDGE                             │
└──────────────────────────────────────────────┘

Runtime Emulation

┌──────────────────────────────────────────────┐
│  LOCAL EMULATOR (V8 Emulator)                │
│  - Emulates Workers API                      │
│  - Intercepts calls to Bindings              │
│  - Maps calls to local files                 │
│         │                                    │
│         ▼                                    │
│  YOUR CODE                                   │
└──────────────────────────────────────────────┘

Summary

ItemValue
Primary CLIwrangler
Emulatorwrangler dev
Secrets File.dev.vars (Local)
Prod Secretswrangler secret put
CI/CD TokenScoped API Token
Loggingwrangler tail

Key takeaways:

  • Runtime parity is non-negotiable. Always use wrangler dev to simulate the V8 isolate environment; don’t rely on Node-only testing.
  • Secrets must be encrypted. Never check secrets into source control. Use .dev.vars for local dev and the Wrangler secret store for production.
  • Use scoped API Tokens. Limit CI/CD access to only the resources the deployment needs; never use global account-wide keys in automation.
  • Environments are for isolation. Separate your dev, staging, and production data using Wrangler environments and distinct configurations.
  • Real-time debugging. Use wrangler tail as your primary mechanism for inspecting live production traffic when things go wrong.

Remember: Wrangler is the extension of your development environment into the Cloudflare infrastructure. By mastering the CLI, you gain the ability to develop, test, debug, and deploy with the same confidence as if you were working on a local machine, but with the massive scale and reliability of the global edge.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!