Template Gallery

These templates are simple building blocks for developing Workers scripts.

Boilerplates

Skeletons that are useful when starting a project. Requires installation of Wrangler.

Hello World

Simple Hello World in JS

Paste this into your terminal:

Hello World Rust

Simple Hello World in Rust

Paste this into your terminal:

Router

Selects the logic based on the request method and URL. Use with REST APIs or apps that require routing logic.

Paste this into your terminal:

Static

Generates a fully functioning HTML page from raw HTML or sends raw JSON defined within your script.

Paste this into your terminal:

Snippets

Copy pasteable code that can be used in a new or existing project.

Aggregate Requests

Sends two GET request to two urls and aggregates the responses into one response.

Copy into a Worker script:
async function handleRequest(request) { const init = { headers: { 'content-type': type, }, } const responses = await Promise.all([fetch(url1, init), fetch(url2, init)]) const results = await Promise.all([gatherResponse(responses[0]), gatherResponse(responses[1])]) return new Response(results, init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) /** * gatherResponse awaits and returns a response body as a string. * Use await gatherResponse(..) in an async function to get the response body * @param {Response} response */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get('content-type') if (contentType.includes('application/json')) { return await response.json() } else if (contentType.includes('application/text')) { return await response.text() } else if (contentType.includes('text/html')) { return await response.text() } else { return await response.text() } } /** * Example someHost is set up to return JSON responses * Replace url1 and url2 with the hosts you wish to * send requests to * @param {string} url the URL to send the request to */ const someHost = 'https://workers-tooling.cf/demos' const url1 = someHost + '/requests/json' const url2 = someHost + '/requests/json' const type = 'application/json;charset=UTF-8'

Bulk Redirects

Redirects requests to certain URLs based a mapped object to the request’s URL.

Copy into a Worker script:
async function handleRequest(request) { let requestURL = new URL(request.url) let path = requestURL.pathname.split('/redirect')[1] let location = redirectMap.get(path) if (location) { return Response.redirect(location, 301) } // If in map, return the original request return fetch(request) } addEventListener('fetch', async event => { event.respondWith(handleRequest(event.request)) }) const externalHostname = 'workers-tooling.cf' const redirectMap = new Map([ ['/bulk1', 'https://' + externalHostname + '/redirect2'], ['/bulk2', 'https://' + externalHostname + '/redirect3'], ['/bulk3', 'https://' + externalHostname + '/redirect4'], ['/bulk4', 'https://google.com'], ])

Fetch HTML

Sends a request to a remote server, reads HTML from the response, then serves that HTML.

Copy into a Worker script:
async function handleRequest(request) { const init = { headers: { 'content-type': 'text/html;charset=UTF-8', }, } const response = await fetch(url, init) const results = await gatherResponse(response) return new Response(results, init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) /** * gatherResponse awaits and returns a response body as a string. * Use await gatherResponse(..) in an async function to get the response body * @param {Response} response */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get('content-type') if (contentType.includes('application/json')) { return await response.json() } else if (contentType.includes('application/text')) { return await response.text() } else if (contentType.includes('text/html')) { return await response.text() } else { return await response.text() } } /** * Example someHost at url is set up to respond with HTML * Replace url with the host you wish to send requests to * */ const someHost = 'https://workers-tooling.cf/demos' const url = someHost + '/static/html'

Fetch JSON

Sends a GET request and reads in JSON from the response.

Copy into a Worker script:
async function handleRequest(request) { const init = { headers: { 'content-type': type, }, } const responses = await Promise.all([fetch(url1, init), fetch(url2, init)]) const results = await Promise.all([gatherResponse(responses[0]), gatherResponse(responses[1])]) return new Response(results, init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) /** * gatherResponse awaits and returns a response body as a string. * Use await gatherResponse(..) in an async function to get the response body * @param {Response} response */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get('content-type') if (contentType.includes('application/json')) { return await response.json() } else if (contentType.includes('application/text')) { return await response.text() } else if (contentType.includes('text/html')) { return await response.text() } else { return await response.text() } } /** * Example someHost is set up to return JSON responses * Replace url1 and url2 with the hosts you wish to * send requests to * @param {string} url the URL to send the request to */ const someHost = 'https://workers-tooling.cf/demos' const url1 = someHost + '/requests/json' const url2 = someHost + '/requests/json' const type = 'application/json;charset=UTF-8'

Form Data

Serve an HTML form, then read POSTs from that form data.

Copy into a Worker script:
async function handlePostRequest(request) { let reqBody = await readRequestBody(request) let retBody = `The request body sent in was ${reqBody}` return new Response(retBody) } async function handleRequest(request) { let retBody = `The request was a GET ` return new Response(retBody) } addEventListener('fetch', event => { const { request } = event const { url } = request if (url.includes('form')) { return event.respondWith(rawHtmlResponse(someForm)) } if (request.method === 'POST') { return event.respondWith(handlePostRequest(request)) } else if (request.method === 'GET') { return event.respondWith(handleRequest(request)) } }) /** * rawHtmlResponse delievers a response with HTML inputted directly * into the worker script * @param {string} html */ async function rawHtmlResponse(html) { const init = { headers: { 'content-type': 'text/html;charset=UTF-8', }, } return new Response(html, init) } /** * readRequestBody reads in the incoming request body * Use await readRequestBody(..) in an async function to get the string * @param {Request} request the incoming request to read from */ async function readRequestBody(request) { const { headers } = request const contentType = headers.get('content-type') if (contentType.includes('application/json')) { const body = await request.json() return JSON.stringify(body) } else if (contentType.includes('application/text')) { const body = await request.text() return body } else if (contentType.includes('text/html')) { const body = await request.text() return body } else if (contentType.includes('form')) { const formData = await request.formData() let body = {} for (let entry of formData.entries()) { body[entry[0]] = entry[1] } return JSON.stringify(body) } else { let myBlob = await request.blob() var objectURL = URL.createObjectURL(myBlob) return objectURL } } const someForm = ` <!DOCTYPE html> <html> <body> <h1>Hello World</h1> <p>This is all generated using a Worker</p> <form action="/demos/requests" method="post"> <div> <label for="say">What do you want to say?</label> <input name="say" id="say" value="Hi"> </div> <div> <label for="to">To who?</label> <input name="to" id="to" value="Mom"> </div> <div> <button>Send my greetings</button> </div> </form> </body> </html>

Post JSON

Sends a POST request with JSON data from the Workers script.

Copy into a Worker script:
async function handleRequest(request) { const init = { body: JSON.stringify(body), method: 'POST', headers: { 'content-type': 'application/json;charset=UTF-8', }, } const response = await fetch(url, init) const results = await gatherResponse(response) return new Response(results, init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) /** * gatherResponse awaits and returns a response body as a string. * Use await gatherResponse(..) in an async function to get the response body * @param {Response} response */ async function gatherResponse(response) { const { headers } = response const contentType = headers.get('content-type') if (contentType.includes('application/json')) { return await response.json() } else if (contentType.includes('application/text')) { return await response.text() } else if (contentType.includes('text/html')) { return await response.text() } else { return await response.text() } } /** * Example someHost is set up to take in a JSON request * Replace url with the host you wish to send requests to * @param {string} url the URL to send the request to * @param {BodyInit} body the JSON data to send in the request */ const someHost = 'https://workers-tooling.cf/demos' const url = someHost + '/requests/json' const body = { results: ['default data to send'], errors: null, msg: 'I sent this to the fetch', }

Redirect

Redirect a request by sending a 301 or 302 HTTP response

Copy into a Worker script:
async function handleRequest(request) { return Response.redirect(someURLToRedirectTo, code) } addEventListener('fetch', async event => { event.respondWith(handleRequest(event.request)) }) /** * Example Input * @param {Request} url where to redirect the response * @param {number?=301|302} type permanent or temporary redirect */ const someURLToRedirectTo = 'https://www.google.com' const code = 301

Send Raw HTML

Delivers an HTML page from HTML directly in the Worker script.

Copy into a Worker script:
async function handleRequest(request) { const init = { headers: { 'content-type': 'text/html;charset=UTF-8', }, } return new Response(someHTML, init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) const someHTML = `<!DOCTYPE html> <html> <body> <h1>Hello World</h1> <p>This is all generated using a Worker</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen ></iframe> </body> </html> `

Send Raw JSON

Renders a response of type application/json to the client

Copy into a Worker script:
async function handleRequest(request) { const init = { headers: { 'content-type': 'application/json;charset=UTF-8', }, } return new Response(JSON.stringify(someJSON), init) } addEventListener('fetch', event => { return event.respondWith(handleRequest(event.request)) }) const someJSON = { result: ['some', 'results'], errors: null, msg: 'this is some random json', }

Featured Projects

More boilerplate projects. Requires installation of Wrangler.

The gallery is actively growing. The template creator allows you to share templates. Host a public repo, and then run wrangler generate https://github.com/<your-repo>. For archived recipes see the old docs.

Binast-Cf-Worker

Serve BinAST via a Cloudflare Worker

Paste this into your terminal:

Img-Color-Worker

Retrieve the dominant color of a PNG or JPEG image

Paste this into your terminal:
wrangler generate my-app https://github.com/xtuc/img-color-worker