Fetch Handler
Background
Incoming HTTP requests to a Worker are passed to the fetch()
handler as a request object. To respond to the request with a response, return a Response
object:
export default { async fetch(request, env, ctx) { return new Response('Hello World!'); },
};
Parameters
request
Request
- The incoming HTTP request.
env
object
- The bindings assigned to the Worker. As long as the environment has not changed, the same object (equal by identity) is passed to all requests.
context.waitUntil(promisePromise)
:void
- Refer to
waitUntil
.
- Refer to
context.passThroughOnException()
:void
- Refer to
passThroughOnException
.
- Refer to
Lifecycle methods
When responding to a HTTP request, the fetch
handler may use any of the following methods to augment or control how the request is handled.
context.waitUntil()
The waitUntil()
method extends the lifetime of the fetch
event. It accepts a Promise
-based task which the Workers runtime will execute before the handler terminates but without blocking the response. For example, this is ideal for caching responses or handling logging.
You can call waitUntil()
multiple times. Similar to Promise.allSettled
, even if a promise passed to one waitUntil
call is rejected, promises passed to other waitUntil()
calls will still continue to execute.
export default { async fetch(request, env, context) { // Forward / Proxy original request let res = await fetch(request);
// Add custom header(s) res = new Response(res.body, res); res.headers.set('x-foo', 'bar');
// Cache the response // NOTE: Does NOT block / wait context.waitUntil(caches.default.put(request, res.clone()));
// Done return res; },
};
context.passThroughOnException()
The passThroughOnException
method allows a Worker to fail open, and pass a request through to an origin server when a Worker throws an unhandled exception. This can be useful when using Workers as a layer in front of an existing service, allowing the service behind the Worker to handle any unexpected error cases that arise in your Worker.
export default { async fetch(request, env, context) { // Proxy to origin on unhandled/uncaught exceptions context.passThroughOnException(); throw new Error('Oops'); },
};
Related resources
- Write your Worker code in ES modules syntax for an optimized experience.