Modify HTTP requests with Cloudflare Workers.
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:
Add a worker by modifying your install.json
. Then, define the path to your Worker with the src
field.
install.json
{
"resources": [...],
"hooks": [...],
"workers": [
{
"src": "./worker.js",
}
]
}
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.
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:
Note that an App may contain only one 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.
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))
})
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.
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.
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.
addEventListener('fetch', event => {
if(event.request.url.includes("custom-route"))
event.respondWith(handleCustomRequest(event.request))
else
event.respondWith(fetch(event.request))
})