Last active
June 12, 2025 10:05
-
-
Save FrancescoPassanti/59142c63bbb3fd72aa41a9d882dd213b to your computer and use it in GitHub Desktop.
Cloudflare Workers - Hello world
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
addEventListener("fetch", event => { | |
// The call to .respondWith() lets the Workers runtime intercept the request in order to send back a custom response. | |
event.respondWith(handleRequest(event.request)) | |
}) | |
// custom function that receives as input the request object and returns a response object | |
async function handleRequest(request) { | |
return new Response("Hello worker!", { | |
headers: { "content-type": "text/plain" } | |
}) | |
} | |
/* | |
The request object is composed of: | |
- body | |
- cf (CF props https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties) | |
- headers | |
- method | |
- url | |
Demo for CF object https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment