Modify HTTP requests with Cloudflare Workers.

Cloudflare's App Workers Beta is now closed. We are no longer accepting new apps that contain Workers scripts to focus on improving the Workers development experience.

Cloudflare Workers can be packaged in a Cloudflare App for Apps with Workers beta users. Fill out this form to request beta access.

This enables powerful sharing of Workers functionality like:

Declaring a Worker

Add a worker by modifying your install.json. Then, define the path to your Worker with the src field.

While install.workers is passed as an array, only a single entry is currently supported.

install.json
{
  "resources": [...],
  "hooks": [...],
  "workers": [
   {
     "src": "./worker.js",
   }
   ]
 }

Writing your Worker

The worker uses the Cloudflare Worker syntax which is based of off MDN Service Worker API. More instructions on how to create a worker can be found here.

worker.js
async function workerFn(request) {
  return new Response(“foo”)
}
addEventListener('fetch', event => {
  event.respondWith(workerFn(event.request))
})

A Worker installed through an App is nearly identical to a regular Cloudflare Worker, but with a few notable differences:

Configuring Your Worker

A Workers script can access user configuration options. The environment varibles - INSTALL_OPTIONS, INSTALL_PRODUCT,INSTALL_ID - will be exposed as global variables in your Workers script.

worker.js
async function workerFn(request) {
  const siteUserAgents = INSTALL_OPTIONS.UserAgents // UserAgents is an option configured by the user during installation
  return request
}
addEventListener('fetch', event => {
  event.respondWith(workerFn(event.request))
})

Installing Your App

Before the installation is finalized, the customer will receive a confirmation dialog informing the user that your App contains a Worker.

Your Workers script and Worker related environment variables will be installed on the user’s domain. Once a site has installed an App Worker, every request made to that site will run through your Worker.

Routing a Worker

A Worker in a Cloudflare App will execute on every request to the website. This is different than using Cloudflare Workers directly, which are mapped via routes. Any routing in an App Worker must be handled in the Workers script. To handle route and condition-based requests, configure the Worker to return custom responses.

worker.js
addEventListener('fetch', event => {
  if(event.request.url.includes("custom"))
    event.respondWith(handleCustomRequest(event.request))
  else
    event.respondWith(fetch(event.request))
})

For more information on conditional routing see: Cloudflare Workers Routing.

worker.js
addEventListener('fetch', event => {
  if(event.request.url.includes("custom-route"))
    event.respondWith(handleCustomRequest(event.request))
  else
    event.respondWith(fetch(event.request))
})