Cloudflare Docs
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

Get started guide

Cloudflare Workers is a serverless application platform running on Cloudflare’s global cloud network in over 200 cities around the world, offering both free and paid plans .

Learn more about how Workers works .

This guide will instruct you through setting up a Cloudflare account to deploying your first Worker script.


1. Sign up for a Workers account

Before you can start publishing your Workers on your own domain or a free *.workers.dev subdomain, you must sign up for a Cloudflare Workers account.

Sign up

The signup process will guide you through choosing a *.workers.dev subdomain and verifying your email address, both of which are required to publish.


2. Install the Workers CLI

Installing wrangler, the Workers CLI, gives you the freedom to init , dev , and publish your Workers projects from the comfort of your development environment.

To install wrangler, ensure you have npm installed, preferably using a Node version manager like Volta or nvm to avoid permission issues or to easily change Node.js versions, then run:

$ npm install -g wrangler

or install with yarn:

$ yarn global add wrangler

3. Configure the Workers CLI

With installation complete, wrangler will need access to a Cloudflare OAuth token to manage Workers resources on your behalf.

Run the command wrangler login, which will automate this process.

Wrangler will attempt to automatically open your web browser to complete the login process to your Cloudflare account. If you have issues completing this step or you do not have access to a browser GUI, you can copy and paste the URL generated by wrangler login in your terminal into a browser and log in.

$ wrangler login
Allow Wrangler to open a page in your browser? [y/n]
y
💁 Opened a link in your default browser: https://dash.cloudflare.com/oauth2/...

Open the browser, log in to your account, and select Allow. This will send an OAuth Token to Wrangler so it can deploy your scripts to Cloudflare.


4. Initialize a new project

Wrangler’s init command will create a new project. The init command will give you options to choose between TypeScript and JavaScript as well as the ability to generate a starter file. Run:

~/ $ wrangler init my-worker

Wrangler will create a directory called src and populate it with the contents of the starter file, in this case the default template. Wrangler will automatically configure the wrangler.toml file in the project’s root with the name = "my-worker".

~/ $ cd my-worker
~/my-worker $ ls
node_modules package-lock.json package.json src wrangler.toml
~/my-worker $ cat wrangler.toml
name = "my-worker"
main = "src/index.js"
compatibility_date = "2022-05-03"

Refer to the Quick Starts page to see a complete list of starter templates.


5. Write code

With your new project generated, you can begin to write your code.

5a. Understanding Hello World

Fundamentally, a Workers application consists of two parts:

  1. An event listener that listens for FetchEvents , and
  2. An event handler that returns a Response object which is passed to the event’s .respondWith() method.

When a request is received on one of Cloudflare’s edge servers for a URL matching a Workers script, it passes the request to the Workers runtime. This dispatches a FetchEvent in the isolate where the script is running.

~/my-worker/index.js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
return new Response('Hello worker!', {
headers: { 'content-type': 'text/plain' },
});
}

Below is an example of the request response workflow:

  1. 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.

  2. The call to .respondWith() lets the Workers runtime intercept the request in order to send back a custom response (in this example, the plain text “Hello worker!”).

    • The FetchEvent handler typically culminates in a call to the method .respondWith() with either a Response or Promise<Response> that determines the response.

    • The FetchEvent object also provides two other methods to handle unexpected exceptions and operations that may complete after a response is returned.

Learn more about the FetchEvent lifecycle .

5b. Routing and filtering requests

After writing a basic script for all requests, the next step is generating a dynamic response based on the requests the Worker script is receiving. This is often referred to as routing.

Option 1: Manually route requests

Use standard JavaScript branching logic, such as if/else or switch statements, to conditionally return different responses or execute different handlers based on the request:

~/my-worker/index.js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
let response;
if (request.method === 'POST') {
response = await generate(request);
} else {
response = new Response('Expected POST', { status: 500 });
}
// ...
}

It is common to route requests based on:

  • request.method — for example, GET or POST.
  • request.url — for example, filter based on query parameters or the pathname.
  • request.headers — filter based on specific headers.

Refer to a full list of all properties of a Request object .

In addition to standard request properties, the Workers platform populates the request with a cf object , containing many useful properties, for example, the region or timezone.

Option 2: Use a template for routing on URL

For more complex routing, it is recommended to use a library. The Workers router starter template provides an API similar to ExpressJS for handling requests based on HTTP methods and paths:

$ git clone https://github.com/cloudflare/worker-template-router
$ cd worker-template-router
$ npm install

This starter is used in the tutorial for building a Slack Bot .

5c. Make use of runtime APIs

The example outlined in this guide is a starting point. There are many Workers runtime APIs available to manipulate requests and generate responses. For example, you can use the HTMLRewriter API to parse and dynamically transform HTML, use the Cache API to retrieve data from and put data into the Cloudflare cache , compute a custom response right from the edge, redirect the request to another service, and more.

For inspiration, refer to Built with Workers for a showcase of projects.


6. Preview your project

~/my-worker $ wrangler dev
⬣ Listening at http://localhost:8787
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ [b] open a browser, [d] open Devtools, [l] turn on local mode, [c] clear console, [x] to exit │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

This command will build your project, run it locally, and return a URL for you to visit to preview the Worker.


(Optional) Configure for deploying to a registered domain

To publish your application on a zone you own, and not a *.workers.dev subdomain, you can add a route key to your wrangler.toml file.

You can get your zone_id with the following steps:

  1. Log in to your Cloudflare account and select the desired zone.
  2. If not already there, navigate to Overview in the dashboard.
  3. Scroll down until you see Zone ID on the right.
  4. Click Click to copy below the input.

Wrangler’s environments feature allows you to deploy the same project to multiple places under multiple names. For a complete guide on how to configure environments, refer to the environments page .

To add a production environment, pass in a zone_id and route:

wrangler.toml
name = "my-worker"
# The route pattern your Workers application will be served at
route = "example.com/*"

The route key here is a route pattern , which can contain wildcards.

If your route is configured to a hostname, you will need to add a DNS record to Cloudflare to ensure that the hostname can be resolved externally. If your Worker acts as your origin (that is, the request terminates in a Worker), you must add a DNS record.

You may enter a placeholder AAAA record pointing to 100::, which must be proxied through Cloudflare (orange-cloud in the DNS settings). This value specifically is the reserved IPv6 discard prefix but is not the only value allowed. For example, you may also use an A record pointed to 192.0.2.1 or a CNAME pointed to any resolvable target.

Whichever method you choose, your record must be proxied through Cloudflare (orange-clouded) and resolve successfully.


8. Publish your project

With your project configured, you can now publish your Worker.

To deploy to your *.workers.dev subdomain, run:

Publish to workers.dev
~/my-worker $ wrangler publish

(Optional) Publish your project to a registered domain

To deploy the production environment set in your wrangler.toml file in the optional configuration step , pass the --env flag to the command:

Publish to example.com
~/my-worker $ wrangler publish --env production

For more information on environments, refer to the Wrangler documentation .

You can also configure a GitHub repository to automatically deploy every time you git push. You can do this by either using the Workers GitHub action, or by writing your own GitHub action and manually configuring the necessary GitHub secrets.


Next steps

This is just the beginning of what you can do with Cloudflare Workers. To do more with Workers, refer to the Tutorials section.