Workers Request and Response Handling
In this tutorial, you'll learn about Workers Request and Response Handling. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Cloudflare Workers provides the standard Request and Response Web API objects, allowing you to inspect incoming HTTP requests, modify their properties, construct new responses, and forward requests to origin servers or external APIs from the edge.
Why Request and Response Handling Matters
Every HTTP API, web application, and middleware layer depends on understanding and manipulating requests and responses. Workers lets you intercept, inspect, and transform HTTP traffic at the edge -- before it reaches your origin. This enables use cases such as request validation, header modification, response Caching, authentication checks, and A/B testing without any changes to your backend. Mastery of the JavaScript Request and Response API is foundational to all Cloudflare Workers development.
Real-world use: An e-commerce platform validates authentication tokens in a Worker before requests reach the origin server. Invalid tokens receive a 401 response at the edge, reducing origin load by 40 percent and improving response times for unauthenticated users.
Request-Response Lifecycle
flowchart TD
C[Client] --> REQ[HTTP Request]
REQ --> W[Worker fetch handler]
W --> INSPECT[Inspect method, headers, body]
INSPECT --> MODIFY[Modify or forward]
MODIFY --> ORIGIN[Origin Server]
MODIFY --> DIRECT[Direct Response]
ORIGIN --> RES[HTTP Response]
DIRECT --> RES
RES --> C
style W fill:#f90,color:#fff
style RES fill:#f90,color:#fff
Inspecting the Incoming Request
Access method, URL, headers, and body from the incoming request.
export default {
async fetch(request) {
const method = request.method;
const url = new URL(request.url);
const userAgent = request.headers.get('User-Agent');
const body = await request.text();
return new Response(JSON.stringify({
method,
path: url.pathname,
query: Object.fromEntries(url.searchParams),
userAgent,
bodyLength: body.length
}), { headers: { 'Content-Type': 'application/json' } });
}
}
Expected output: A POST to https://worker.example.com/api/login?redirect=/dashboard with body {"user":"alice"} returns {"method":"POST","path":"/api/login","query":{"redirect":"/dashboard"},"userAgent":"curl/8.0","bodyLength":19}.
Modifying and Forwarding Requests
Clone the request, modify headers, and forward it to an origin.
export default {
async fetch(request) {
const url = new URL(request.url);
url.hostname = 'origin.example.com';
const modifiedRequest = new Request(url, {
method: request.method,
headers: request.headers,
body: request.body
});
modifiedRequest.headers.set('X-Forwarded-By', 'Cloudflare-Worker');
const response = await fetch(modifiedRequest);
const modifiedResponse = new Response(response.body, response);
modifiedResponse.headers.set('X-Edge-Cached', 'true');
return modifiedResponse;
}
}
Expected output: The Worker rewrites the host to origin.example.com, adds an X-Forwarded-By header to the outgoing request, and appends an X-Edge-Cached header to the response sent back to the client.
Returning CORS Headers for API Requests
Handle cross-origin requests by adding CORS headers to responses.
export default {
async fetch(request) {
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400'
}
});
}
const response = await fetch('https://api.example.com/data');
const corsResponse = new Response(response.body, response);
corsResponse.headers.set('Access-Control-Allow-Origin', '*');
return corsResponse;
}
}
Expected output: Preflight OPTIONS requests receive CORS headers without reaching the origin. Regular requests also return with Access-Control-Allow-Origin: *, enabling browser-based clients from any domain to call the API.
Common Errors
| Error | Cause | Fix |
|---|---|---|
Body already consumed |
Reading request.body or request.text() twice |
Clone the request first with request.clone() |
Cannot modify immutable headers |
Mutating headers on an incoming request | Create a new Request or Response with modified headers |
Invalid URL |
Passing a relative URL to fetch |
Always provide absolute URLs inside Workers |
TypeError: Failed to fetch |
Destination server is unreachable or returning errors | Add error handling with try/catch around fetch |
Response size exceeds limit |
Response body larger than 100MB | Use TransformStream for streaming large payloads |
Practice Questions
- Why must you clone a Request before reading its body twice in Workers?
- What HTTP status code should a preflight CORS handler return?
- How do you modify headers on an outgoing request without mutating the original?
FAQ
Summary
HTTP request and response handling is the core of Cloudflare Workers development. You inspect incoming requests, modify headers and bodies, forward to origins, and construct custom responses -- all at the edge. Cloning requests before reading bodies and creating new Response objects for header modification are essential patterns. These techniques power the request inspection layer in Durga Antivirus Pro's web scanning engine. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro -- security-first tools for the modern web.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro