Cloudflare Workers Cheat Sheet

Quick reference for Cloudflare Workers: Wrangler CLI, request handling, KV storage, D1 database, R2 object storage, and Cron Triggers. Build and deploy serverless apps at the edge.

CLI & Setup Request Handling KV Storage D1 Database R2 Storage Cron Triggers

CLI & Setup

npm create cloudflare@latest my-app Scaffold a new Cloudflare Workers project
npx wrangler init my-app Initialize a Workers project with wrangler
npx wrangler dev Start a local development server with hot reload
npx wrangler deploy Deploy the Worker to Cloudflare\'s edge network
npx wrangler tail Stream live logs from a deployed Worker
npx wrangler secret put MY_SECRET Set an encrypted environment variable
npx wrangler whoami Show the currently authenticated Cloudflare account
npx wrangler delete Delete a deployed Worker (use with caution)

Request Handling

export default { async fetch(request, env, ctx) { return new Response("Hello"); } } Basic Worker fetch handler (ES module syntax)
const url = new URL(request.url) Parse the request URL
const method = request.method Get the HTTP method (GET, POST, etc.)
const body = await request.json() Parse the request body as JSON
const headers = Object.fromEntries(request.headers) Convert request headers to a plain object
request.cf.country Access the client\'s country from Cloudflare metadata
return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } }) Return a JSON response with proper headers
return Response.redirect("https://example.com", 301) Return a redirect response
ctx.waitUntil(promise) Extend Worker lifetime for background tasks after response

KV Storage

npx wrangler kv namespace create MY_KV Create a new KV namespace
await env.MY_KV.put("key", "value") Write a key-value pair to KV
await env.MY_KV.put("key", "value", { expirationTtl: 3600 }) Write a key with a TTL of 1 hour
const value = await env.MY_KV.get("key") Read a value from KV by key
const data = await env.MY_KV.get("key", { type: "json" }) Read and parse a JSON value from KV
await env.MY_KV.delete("key") Delete a key from KV
const list = await env.MY_KV.list({ prefix: "user:" }) List keys with a specific prefix
await env.MY_KV.put("key", value, { metadata: { created: Date.now() } }) Store a value with associated metadata

D1 Database

npx wrangler d1 create my-database Create a new D1 SQLite database
npx wrangler d1 execute my-database --command "SELECT 1" Run a SQL command against D1 remotely
npx wrangler d1 execute my-database --file schema.sql Execute a SQL file against D1
const { results } = await env.DB.prepare("SELECT * FROM users").all() Query all rows from a D1 table
await env.DB.prepare("INSERT INTO users (name) VALUES (?)").bind("Alice").run() Insert a row with a parameterized query
const row = await env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(1).first() Query a single row by ID
const batch = await env.DB.batch([ env.DB.prepare("INSERT ..."), env.DB.prepare("UPDATE ...") ]) Execute multiple statements in a batch (transaction)
npx wrangler d1 migrations create my-database add_email Create a new migration file for D1

R2 Storage

npx wrangler r2 bucket create my-bucket Create a new R2 storage bucket
await env.MY_BUCKET.put("file.txt", "Hello World") Upload a file to R2
await env.MY_BUCKET.put("image.png", request.body) Upload a binary file from request body to R2
const object = await env.MY_BUCKET.get("file.txt") Retrieve a file from R2
const text = await object.text() Read R2 object contents as text
await env.MY_BUCKET.delete("file.txt") Delete a file from R2
const list = await env.MY_BUCKET.list({ prefix: "images/" }) List objects with a specific prefix in R2
await env.MY_BUCKET.put("key", data, { httpMetadata: { contentType: "image/png" } }) Upload with custom content type metadata

Cron Triggers

export default { async scheduled(event, env, ctx) { /* ... */ } } Define a scheduled (cron) event handler
[triggers] crons = ["0 * * * *"] Run the Worker every hour (in wrangler.toml)
[triggers] crons = ["*/5 * * * *"] Run the Worker every 5 minutes
[triggers] crons = ["0 0 * * *"] Run the Worker once daily at midnight UTC
event.scheduledTime Get the scheduled execution time as a timestamp
ctx.waitUntil(doWork()) Ensure async work completes before the cron handler exits
npx wrangler dev --test-scheduled Test cron triggers locally via HTTP endpoint
[triggers] crons = ["0 9 * * MON"] Run the Worker every Monday at 9 AM UTC

Try It Live

Test these patterns with our free API Tester. No signup needed.

Open API Tester →
Step-by-Step Guide

How to Test an API Online

Read Guide →

More Cheat Sheets