Examples
Deliver an HTML page from an HTML string directly inside the Worker script.
const html = `<!DOCTYPE html><body> <h1>Hello World</h1> <p>This markup was generated by a Cloudflare Worker.</p></body>`
async function handleRequest(request) { return new Response(html, { headers: { "content-type": "text/html;charset=UTF-8", }, })}
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request))})
Return JSON directly from a Worker script, useful for building APIs and middleware.
addEventListener("fetch", event => { const data = { hello: "world" }
const json = JSON.stringify(data, null, 2)
return event.respondWith( new Response(json, { headers: { "content-type": "application/json;charset=UTF-8" } }) )})
Redirect requests from one URL to another, or from one set of URLs to another set.
const destinationURL = "https://example.com"const statusCode = 301
async function handleRequest(request) { return Response.redirect(destinationURL, statusCode)}
addEventListener("fetch", async event => { event.respondWith(handleRequest(event.request))})
Access custom Cloudflare properties and control how Cloudflare features are applied to every request.
addEventListener("fetch", event => { const data = event.request.cf !== undefined ? event.request.cf : { error: "The `cf` object is not available inside the preview." }
return event.respondWith( new Response(JSON.stringify(data, null, 2), { headers: { "content-type": "application/json;charset=UTF-8" } }) )})
Respond to the Worker request with the response from another website (example.com in this example).
addEventListener("fetch", event => { return event.respondWith( fetch("https://example.com") )})
Allow or deny a request based on a known pre-shared key in a header. This is not meant to replace the WebCrypto API.
/** * @param {string} PRESHARED_AUTH_HEADER_KEY Custom header to check for key * @param {string} PRESHARED_AUTH_HEADER_VALUE Hard coded key value */const PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK"const PRESHARED_AUTH_HEADER_VALUE = "mypresharedkey"
async function handleRequest(request) { const psk = request.headers.get(PRESHARED_AUTH_HEADER_KEY)
if (psk === PRESHARED_AUTH_HEADER_VALUE) { // Correct preshared header key supplied. Fetch request from origin. return fetch(request) }
// Incorrect key supplied. Reject the request. return new Response("Sorry, you have supplied an invalid key.", { status: 403, })}
addEventListener("fetch", event => { event.respondWith(handleRequest(event.request))})
Inspects the incoming request's TLS version and blocks if under TLSv1.2.
async function handleRequest(request) { try { const tlsVersion = request.cf.tlsVersion
// Allow only TLS versions 1.2 and 1.3 if (tlsVersion != "TLSv1.2" && tlsVersion != "TLSv1.3") { return new Response("Please use TLS version 1.2 or higher.", { status: 403, }) }
return fetch(request) } catch (err) { console.error( "request.cf does not exist in the previewer, only in production", ) return new Response("Error in workers script" + err.message, { status: 500, }) }}
addEventListener("fetch", event => { event.respondWith(handleRequest(event.request))})
Resolve requests to your domain to a set of proxy third-party origin URLs.
/** * An object with different URLs to fetch * @param {Object} ORIGINS */const ORIGINS = { "starwarsapi.yourdomain.com": "swapi.dev", "google.yourdomain.com": "www.google.com",}
async function handleRequest(request) { const url = new URL(request.url) // Check if incoming hostname is a key in the ORIGINS object if (url.hostname in ORIGINS) { const target = ORIGINS[url.hostname] url.hostname = target // If it is, proxy request to that third party origin return await fetch(url.toString(), request) }
// Otherwise, process request as normal return await fetch(request)}
addEventListener("fetch", event => { event.respondWith(handleRequest(event.request))})
Redirect requests to certain URLs based on a mapped object to the request's URL.
const externalHostname = "examples.cloudflareworkers.com"
const redirectMap = new Map([ ["/bulk1", "https://" + externalHostname + "/redirect2"], ["/bulk2", "https://" + externalHostname + "/redirect3"], ["/bulk3", "https://" + externalHostname + "/redirect4"], ["/bulk4", "https://google.com"],])
async function handleRequest(request) { const requestURL = new URL(request.url) const path = requestURL.pathname.split("/redirect")[1] const location = redirectMap.get(path) if (location) { return Response.redirect(location, 301) } // If request not in map, return the original request return fetch(request)}
addEventListener("fetch", async event => { event.respondWith(handleRequest(event.request))})
Determine how to cache a resource by setting TTLs, custom cache keys, and cache headers in a fetch request.
async function handleRequest(request) { const url = new URL(request.url)
// Only use the path for the cache key, removing query strings // and always store using HTTPS e.g. https://www.example.com/file-uri-here const someCustomKey = `https://${url.hostname}${url.pathname}`
let response = await fetch(request, { cf: { // Always cache this fetch regardless of content type // for a max of 5 seconds before revalidating the resource cacheTtl: 5, cacheEverything: true, //Enterprise only feature, see Cache API for other plans cacheKey: someCustomKey, }, }) // Reconstruct the Response object to make its headers mutable. response = new Response(response.body, response)
// Set cache control headers to cache on browser for 25 minutes response.headers.set("Cache-Control", "max-age=1500") return response}
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request))})
Examine the contents of a Headers object by logging to console with a Map.
async function handleRequest(request) { let requestHeaders = JSON.stringify([...request.headers]) console.log(new Map(request.headers))
return new Response("Hello world")}
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request))})
Rewrite URL links in HTML using the HTMLRewriter. This is useful for JAMstack websites.
const OLD_URL = "developer.mozilla.org"const NEW_URL = "mynewdomain.com"
async function handleRequest(req) { const res = await fetch(req) return rewriter.transform(res)}
class AttributeRewriter { constructor(attributeName) { this.attributeName = attributeName } element(element) { const attribute = element.getAttribute(this.attributeName) if (attribute) { element.setAttribute( this.attributeName, attribute.replace(OLD_URL, NEW_URL), ) } }}
const rewriter = new HTMLRewriter() .on("a", new AttributeRewriter("href")) .on("img", new AttributeRewriter("src"))
addEventListener("fetch", event => { event.respondWith(handleRequest(event.request))})