Isaac.

Cloudflare Workers Environment Variables and Secrets

Manage configuration and sensitive data in Cloudflare Workers.

By EMEPublished: February 20, 2025
cloudflare workersenvironment variablessecretsconfiguration

A Simple Analogy

Environment variables in Workers are like a notes app for your code. Store configuration details that change per environment.


Why Configuration?

  • Environment-specific: Different settings per deployment
  • Security: Don't hardcode secrets
  • Flexibility: Change without redeploying
  • Secrets: Sensitive data stays safe
  • Rotation: Update credentials easily

wrangler.toml Setup

[env.production]
name = "api-worker-prod"
route = "https://api.example.com/*"

[env.production.env]
DATABASE_URL = "postgresql://prod-db"
API_KEY = "sk_prod_xxx"

[env.staging]
name = "api-worker-staging"
route = "https://staging.example.com/*"

[env.staging.env]
DATABASE_URL = "postgresql://staging-db"
API_KEY = "sk_staging_xxx"

Using Variables

export default {
  async fetch(request) {
    const dbUrl = env.DATABASE_URL;
    const apiKey = env.API_KEY;
    
    const response = await fetch(`${dbUrl}/query`);
    // Use variables in your code
  }
}

interface Env {
  DATABASE_URL: string;
  API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env) {
    // Type-safe access
    console.log(env.DATABASE_URL);
  }
}

Secrets Management

# Store secret in production environment
wrangler secret put API_KEY --env production
# Then paste the secret value

# Store multiple secrets
wrangler secret put DATABASE_PASSWORD
wrangler secret put JWT_SECRET
wrangler secret put ENCRYPTION_KEY

# List secrets
wrangler secret list

# Delete secret
wrangler secret delete API_KEY

Using Secrets

export default {
  async fetch(request, env) {
    const apiKey = env.API_KEY;      // From [env] section
    const dbPass = env.DATABASE_PASSWORD;  // From secrets
    
    // Use in API calls
    const response = await fetch('https://api.example.com/data', {
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    });
    
    return response;
  }
}

KV Namespace Configuration

[[kv_namespaces]]
binding = "CACHE"
id = "abc123"
preview_id = "xyz789"

[[kv_namespaces]]
binding = "SESSIONS"
id = "def456"
preview_id = "ijk012"
export default {
  async fetch(request, env) {
    const cached = await env.CACHE.get('key');
    await env.SESSIONS.put('session-id', JSON.stringify(data));
  }
}

Best Practices

  1. Never hardcode: Use environment variables
  2. Rotate secrets: Update periodically
  3. Scope access: Limit who can view secrets
  4. Version control: Commit config structure, not values
  5. Document: List required variables

Related Concepts

  • Durable Objects
  • Workers Analytics
  • Cron triggers
  • Environment management

Summary

Configure Cloudflare Workers with wrangler.toml for environment variables and store secrets securely using the wrangler CLI.