Using Service Worker syntax
A Worker written in Service Worker syntax consists of two parts:
- An event listener that listens for
FetchEvents
, and - An event handler that returns a Response object which is passed to the event’s
.respondWith()
method.
When a request is received on one of Cloudflare’s global network servers for a URL matching a Workers script, it passes the request to the Workers runtime. This dispatches a FetchEvent
in the isolate where the script is running.
~/my-worker/index.jsaddEventListener('fetch', event => { event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) { return new Response('Hello worker!', { headers: { 'content-type': 'text/plain' }, });
}
Below is an example of the request response workflow:
An event listener for the
FetchEvent
tells the script to listen for any request coming to your Worker. The event handler is passed theevent
object, which includesevent.request
, aRequest
object which is a representation of the HTTP request that triggered theFetchEvent
.The call to
.respondWith()
lets the Workers runtime intercept the request in order to send back a custom response (in this example, the plain text “Hello worker!”).The
FetchEvent
handler typically culminates in a call to the method.respondWith()
with either aResponse
orPromise<Response>
that determines the response.The
FetchEvent
object also provides two other methods to handle unexpected exceptions and operations that may complete after a response is returned.
Learn more about the FetchEvent
lifecycle.