Cloudflare Workers Security Guide

To secure Cloudflare Workers, you need to: (1) store secrets with wrangler secret put, never in wrangler.toml, (2) rate limit with Workers KV or Durable Objects, (3) validate every incoming request, JWT included, at the edge, (4) lock CORS down so unknown origins get nothing, and (5) make sure error messages don't leak anything sensitive. This blueprint covers the edge patterns for each.

Setup Time1-2 hours

TL;DR

Workers run at the edge and read secrets through environment variables. Keep anything sensitive in wrangler secrets. Validate every request, rate limit with Workers KV or Durable Objects, and be careful with CORS.

JWT Validation at the Edge Cloudflare

Check the token before the Worker does anything else. No valid signature, no request.

src/index.ts
export interface Env {
  JWT_SECRET: string
  ALLOWED_ORIGINS: string
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // CORS handling
    if (request.method === 'OPTIONS') {
      return handleCors(request, env)
    }

    // Authenticate
    const authHeader = request.headers.get('Authorization')
    if (!authHeader?.startsWith('Bearer ')) {
      return new Response('Unauthorized', { status: 401 })
    }

    const token = authHeader.slice(7)

    try {
      const payload = await verifyJwt(token, env.JWT_SECRET)
      // Token is valid, process request
      return handleRequest(request, payload, env)
    } catch {
      return new Response('Invalid token', { status: 401 })
    }
  },
}

async function verifyJwt(token: string, secret: string) {
  const encoder = new TextEncoder()
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify']
  )

  const [headerB64, payloadB64, signatureB64] = token.split('.')
  const data = encoder.encode(`${headerB64}.${payloadB64}`)
  const signature = base64UrlDecode(signatureB64)

  const valid = await crypto.subtle.verify('HMAC', key, signature, data)
  if (!valid) throw new Error('Invalid signature')

  return JSON.parse(atob(payloadB64))
}

Rate Limiting with KV Cloudflare

One caveat before you copy this. KV is eventually consistent, and Cloudflare's docs say a write can take 60 seconds or more to show up in other locations. So a burst spread across regions can get past the limit. If the limit has to be exact, keep the counter in a Durable Object.

src/rate-limit.ts
export interface Env {
  RATE_LIMIT_KV: KVNamespace
}

export async function rateLimit(
  ip: string,
  env: Env,
  limit = 100,
  window = 60
): Promise<boolean> {
  const key = `rate:${ip}`
  const current = await env.RATE_LIMIT_KV.get(key)

  if (!current) {
    await env.RATE_LIMIT_KV.put(key, '1', { expirationTtl: window })
    return true
  }

  const count = parseInt(current, 10)
  if (count >= limit) {
    return false
  }

  await env.RATE_LIMIT_KV.put(key, String(count + 1), { expirationTtl: window })
  return true
}

// Usage in worker
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const ip = request.headers.get('CF-Connecting-IP') || 'unknown'

    if (!await rateLimit(ip, env)) {
      return new Response('Too many requests', { status: 429 })
    }

    // Process request...
  },
}

Secrets Management

wrangler.toml + CLI
# wrangler.toml - Don't put secrets here!
name = "my-worker"
main = "src/index.ts"

[vars]
ALLOWED_ORIGINS = "https://myapp.com"

# Add secrets via CLI (encrypted, not in source)
# wrangler secret put JWT_SECRET
# wrangler secret put DATABASE_URL

Never put secrets in wrangler.toml. That file usually ends up in git. Use wrangler secret put instead: the value is encrypted and only your Worker can read it at runtime.

Security Checklist

Pre-Launch Checklist

Check Your Workers Security

Scan for edge function vulnerabilities.

Security Blueprints

Cloudflare Workers Security Guide