Edit on Github

Cloudflare Workers Documentation

Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure.

Quick Start

Get Started Begin building and publishing your code from the CLI.

Tutorials

Discover what you can build with these step-by-step tutorials.

Templates

Ready-to-use code to get you started.

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:

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'], ])

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> `
View all templates

Reference

Licenses