Context (ctx
)
The Context API provides methods to manage the lifecycle of your Worker or Durable Object.
Context is exposed via the following places:
- As the third parameter in all handlers, including the
fetch()
handler. (fetch(request, env, ctx)
) - As a class property of the
WorkerEntrypoint
class
waitUntil
ctx.waitUntil()
extends the lifetime of your Worker, allowing you to perform work without blocking returning a response, and that may continue after a response is returned. It accepts a Promise
, which the Workers runtime will continue executing, even after a response has been returned by the Worker’s handler.
waitUntil
is commonly used to:
- Fire off events to external analytics providers. (note that when you use Workers Analytics Engine, you do not need to use
waitUntil
) - Put items into cache using the Cache API
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.
For example:
export default { async fetch(request, env, ctx) { // 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 ctx.waitUntil(caches.default.put(request, res.clone()));
// Done return res; },
};
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, ctx) { // Proxy to origin on unhandled/uncaught exceptions ctx.passThroughOnException(); throw new Error('Oops'); },
};