Cloudflare Docs
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

Using Service Worker syntax

A Worker written in Service Worker syntax consists of two parts:

  1. An event listener that listens for FetchEvents, and
  2. 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.js
addEventListener('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:

  1. An event listener for the FetchEvent tells the script to listen for any request coming to your Worker. The event handler is passed the event object, which includes event.request, a Request object which is a representation of the HTTP request that triggered the FetchEvent.

  2. 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 a Response or Promise<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.