Overview
The Fetch API consists of several core interfaces:Request- Represents an HTTP requestResponse- Represents an HTTP responseHeaders- Manages HTTP headersfetch()- Executes HTTP requests
src/workerd/api/http.h and http.c++
Making requests
The globalfetch() function sends HTTP requests:
Request options
Customize requests with options:Request object
Create reusableRequest objects:
Working with responses
Reading response data
TheResponse object provides multiple methods to read the body:
Response properties
Access response metadata:Creating responses
Return custom responses from your worker:Headers
TheHeaders interface manages HTTP headers:
Request body types
Workerd supports multiple body types:Generator bodies
Workerd supports async generators as request/response bodies:src/workerd/api/tests/fetch-test.js:26
Body mixin
TheBody class (defined in src/workerd/api/http.h:30) is a mixin that provides body-related functionality to both Request and Response.
Body types
Advanced features
Request cloning
Clone requests for multiple uses:Response cloning
Clone responses to read the body multiple times:Redirect handling
Control redirect behavior:Method normalization
With theupper_case_all_http_methods compatibility flag, method names are converted to uppercase:
src/workerd/api/tests/fetch-test.js:10
Error handling
Handle fetch errors gracefully:Best practices
Check response status
Check response status
Always check
response.ok or response.status before processing the body:Stream large responses
Stream large responses
Use
response.body as a ReadableStream for large responses:Reuse request objects
Reuse request objects
Create reusable request templates:
Implementation details
The Fetch API implementation is located in:src/workerd/api/http.h- Header definitions (1300+ lines)src/workerd/api/http.c++- Implementation (3500+ lines)src/workerd/api/headers.h/headers.c++- Headers implementationsrc/workerd/api/blob.h/blob.c++- Blob implementation
Body class provides the extraction algorithm from the Fetch spec and handles various body types through the Initializer OneOf type.
Related APIs
- Headers API - Managing HTTP headers
- Streams API - Processing request/response bodies
- WebSocket API - Upgrading to WebSocket connections