Workers Best Practices
Automate and integrate Workers Best Practices for efficient and reliable serverless development
Workers Best Practices is a community skill for building production-quality Cloudflare Workers, covering request handling patterns, error management, caching strategies, security headers, and observability for edge applications.
What Is This?
Overview
Workers Best Practices provides patterns for building reliable Cloudflare Workers that handle production traffic. It covers request handling with middleware chains, CORS configuration, and method routing for API Workers, error management with structured error responses, retry logic, and graceful degradation, caching strategies using Cache API for response caching and KV for pre-computed data, security headers including Content-Security-Policy, HSTS, and rate limiting at the edge, and observability with structured logging, request tracing, and metrics collection. The skill enables developers to build Workers that are reliable, secure, and observable in production environments.
Who Should Use This
This skill serves developers deploying Cloudflare Workers to handle production API traffic, teams establishing patterns for error handling and caching in edge functions, and engineers implementing security and observability for Workers.
Why Use It?
Problems It Solves
Workers without structured error handling return raw exceptions to clients. Missing CORS headers cause client-side fetch failures from browser applications. Uncached responses to repeated requests waste compute at the edge. Workers without logging make production debugging impossible.
Core Highlights
Middleware pattern chains request processors for auth, logging, and CORS. Cache API stores responses at edge locations for repeated requests. Structured error handler returns consistent JSON error responses. Request logger captures timing, status, and path for observability.
How to Use It?
Basic Usage
// Worker with middleware pattern
type Handler = (
req: Request,
env: Env,
ctx: ExecutionContext
) => Promise<Response>;
function withCORS(
handler: Handler
): Handler {
return async (req, env, ctx) => {
if (req.method ===
'OPTIONS') {
return new Response(null,
{ headers: corsHeaders });
}
const res =
await handler(
req, env, ctx);
for (const [k, v]
of Object.entries(
corsHeaders)) {
res.headers.set(k, v);
}
return res;
};
}
const corsHeaders: Record<
string, string> = {
'Access-Control-Allow-Origin':
'*',
'Access-Control-Allow-Methods':
'GET, POST, OPTIONS',
'Access-Control-Allow-Headers':
'Content-Type, Authorization',
};
function withErrors(
handler: Handler
): Handler {
return async (req, env, ctx) => {
try {
return await handler(
req, env, ctx);
} catch (e: any) {
return Response.json(
{ error: e.message },
{ status: 500 });
}
};
}Real-World Examples
// Caching and logging
function withCache(
ttl: number,
handler: Handler
): Handler {
return async (req, env, ctx) => {
const cache =
caches.default;
const cached =
await cache.match(req);
if (cached) return cached;
const res =
await handler(
req, env, ctx);
const clone = res.clone();
clone.headers.set(
'Cache-Control',
`s-maxage=${ttl}`);
ctx.waitUntil(
cache.put(req, clone));
return res;
};
}
function withLogging(
handler: Handler
): Handler {
return async (req, env, ctx) => {
const start = Date.now();
const res =
await handler(
req, env, ctx);
const duration =
Date.now() - start;
ctx.waitUntil(
logRequest({
method: req.method,
path:
new URL(req.url)
.pathname,
status: res.status,
duration,
}));
return res;
};
}
// Compose middleware
const handler: Handler =
withLogging(
withErrors(
withCORS(
withCache(60,
apiHandler))));
export default {
fetch: handler,
};Advanced Tips
Use ctx.waitUntil for fire-and-forget operations like logging and cache writes that should not block the response. Implement structured logging with JSON format for integration with log aggregation services. Use edge-based rate limiting with Durable Objects for per-client request throttling.
When to Use It?
Use Cases
Build a production API Worker with middleware for CORS, error handling, caching, and logging. Implement edge-level security headers and rate limiting for API protection. Create an observable Worker with structured logging and request tracing.
Related Topics
Cloudflare Workers, middleware patterns, edge caching, CORS, and observability.
Important Notes
Requirements
Cloudflare Workers environment with Cache API access. Wrangler CLI for local development and deployment. Logging service for collecting structured log output.
Usage Recommendations
Do: use middleware composition for cross-cutting concerns like auth, logging, and CORS. Cache responses with appropriate TTLs for read-heavy endpoints. Return structured JSON error responses with consistent status codes.
Don't: catch errors silently without logging for production debugging. Cache responses that contain user-specific data without proper cache keys. Add CORS headers with wildcard origins in production for authenticated APIs.
Limitations
Cache API at the edge is per-location and may have cold starts in less-trafficked regions. Workers CPU time limits restrict middleware chain complexity. Logging from Workers requires external services since there is no built-in log persistence.
More Skills You Might Like
Explore similar skills to enhance your workflow
Pptx Posters
Automated PPTX posters creation and integration for professional visual presentations
Bitwarden Automation
Automate Bitwarden operations through Composio's Bitwarden toolkit via
Fitbit Automation
Automate Fitbit operations through Composio's Fitbit toolkit via Rube MCP
Stripe Best Practices
Apply and integrate best practices for Stripe payments and billing workflows
Brex Automation
Automate Brex operations through Composio's Brex toolkit via Rube MCP
Linkup Automation
Automate Linkup operations through Composio's Linkup toolkit via Rube MCP