Cloudflare Workers/Pages at the edge — Security Pitfalls & Fixes — Practical Guide (Jun 6, 2026)
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 1rem; max-width: 900px; }
h2 { margin-top: 2rem; }
h3 { margin-top: 1.5rem; }
pre { background: #f5f5f5; padding: 1rem; overflow-x: auto; border-radius: 4px; }
code { font-family: Consolas, monospace; }
.audience { font-style: italic; color: #555; }
.social { margin-top: 3rem; font-weight: bold; }
Cloudflare Workers/Pages at the edge — Security Pitfalls & Fixes
Level: Experienced Software Engineers
As of June 6, 2026, this article explores key security considerations when developing with Cloudflare Workers and Cloudflare Pages at the edge, focusing on common security pitfalls and practical fixes. Our guidance is primarily relevant for Workers runtimes from v1 onwards and Page deployments using the Workers platform integration deployed via Cloudflare’s global network.
Prerequisites
This article assumes familiarity with:
- Cloudflare Workers—writing and deploying serverless JavaScript/TypeScript functions.
- Cloudflare Pages basics, including deploying static sites with optional backend functions.
- Edge computing concepts and HTTP security principles.
- Knowledge of authentication, CORS, and HTTP header security best practices.
Ensure you have the latest Wrangler CLI installed (v2.X or newer) to test and deploy Workers locally before production rollout.
Hands-on Steps: Implementing Secure Workers & Pages
1. Secure Environment Variables & Secrets
Use wrangler secrets to inject sensitive credentials into Workers without exposing them in source code or logs.
# Add a secret API token
wrangler secret put MY_API_TOKEN
In code, access securely via the global env or bindings parameter:
// Example Worker module - index.js
export default {
async fetch(request, env) {
const token = env.MY_API_TOKEN;
// Use token securely within your code
}
}
2. Strictly Validate Input and HTTP Headers
Malformed or untrusted requests can lead to injection or XSS attacks. Sanitize query strings, JSON bodies, cookies, and headers before use. Prefer libraries or Cloudflare’s request.json() with error handling to avoid malformed payloads.
3. Configure CORS Carefully
Edge functions often serve resources to various origins. Overpermissive CORS settings (like Access-Control-Allow-Origin: *) undermine security. Instead, whitelist trusted origins or dynamically validate the Origin header:
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
export default {
async fetch(request) {
const origin = request.headers.get('Origin');
const headers = new Headers();
if (allowedOrigins.includes(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
headers.set('Access-Control-Allow-Headers', 'Authorization, Content-Type');
}
if (request.method === 'OPTIONS') {
return new Response(null, { status: 204, headers });
}
// Handle actual request
return new Response('Hello from edge', { headers });
}
}
4. Use Secure HTTP Headers
At the edge, setting security-related HTTP headers can mitigate common attacks:
Content-Security-Policy— Limit sources of scripts and styles to reduce XSS risks.X-Content-Type-Options: nosniff— Prevent MIME sniffing.Strict-Transport-Security— Enforce HTTPS connections.Referrer-Policy— Control referrer data exposure.
Example in Workers:
const securityHeaders = {
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self';",
'X-Content-Type-Options': 'nosniff',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'Referrer-Policy': 'strict-origin-when-cross-origin',
};
export default {
async fetch(request) {
const response = await fetch(request);
const newHeaders = new Headers(response.headers);
Object.entries(securityHeaders).forEach(([key, value]) => {
newHeaders.set(key, value);
});
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
}
5. Protect Authentication & Authorization Logic
When implementing auth, beware of these edge-specific concerns:
- Secure cookies: Use
Secure,HttpOnly, andSameSiteattributes on tokens transmitted via cookies. - Token freshness: Validate and periodically refresh JWTs or API tokens. Avoid storing tokens in Workers KV unencrypted.
- Replay attack mitigation: Use anti-CSRF tokens and ensure idempotent unsafe methods verify authenticity.
Common Security Pitfalls
1. Over-broad CORS Configuration
Setting Access-Control-Allow-Origin: * for endpoints that require authentication leaks credentials to untrusted origins. Instead, explicitly allow known domains.
2. Leaking Secrets in Response or Logs
Accidentally echoing environment variables or stack traces in error responses can expose secrets. Always sanitise error messages and avoid including sensitive data in response bodies or log outputs.
3. Ignoring Rate Limiting at Edge
Cloudflare provides edge-based rate limiting (configurable via firewall or Workers KV counters). Without it, brute force or DOS attacks can overwhelm your backend or Worker, causing outages or escalating costs.
4. Misconfigured Redirects and Open Redirect Risks
Redirects that accept user input without validation can enable phishing and open redirect attacks. Always validate redirect targets against a whitelist or use relative paths only.
5. Assumptions about Trusted Headers
Headers like X-Forwarded-For or CF-Connecting-IP can be spoofed if your Worker does not run behind Cloudflare’s proxy. Ensure your Worker is only accessible through Cloudflare’s proxy or verify the request source to trust such headers.
Validation: How to Test Your Edge Security
- Static analysis and linting: Use
eslint-plugin-securityor equivalents integrated into your CI pipeline. - Penetration testing: Use tools like OWASP ZAP or Amass to simulate attacks on your endpoints.
- Security headers check: Automated scans with securityheaders.com or
curl -Ifor quick inspection. - CORS testing: Use browser developer tools to review preflight OPTIONS requests and CORS response headers.
- Secrets exposure testing: Search codebase and logs post-deployment for accidental secret leaks.
Checklist / TL;DR
- Use Wrangler secrets to safeguard environment variables.
- Validate and sanitise all input to Workers, including headers and query parameters.
- Implement strict, tailored CORS policies, avoiding wildcards in sensitive routes.
- Set and verify security headers like Content-Security-Policy and HSTS globally.
- Secure authentication cookies and safeguard token storage and validation.
- Leverage Cloudflare’s rate limiting and bot management at the edge.
- Carefully validate redirect URLs to prevent open redirect vulnerabilities.
<