Skip to content
Visit Workers on GitHub
Set theme to dark (⇧+D)

Getting started

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.

1. Sign up for a Workers account

Before you can start publishing your Workers on your own domain or a free subdomain, you’ll need to sign up for a Cloudflare Workers account.

Sign up

The signup process will guide you through choosing a 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 generate, configure, build, preview, and publish your Workers projects from the comfort of your dev environment.

To install wrangler, ensure you have npm installed, then run:

$ npm install -g @cloudflare/wrangler

Then run wrangler --version to confirm that the installation was successful:

$ wrangler --version👷 ✨  wrangler 1.12.2

3. Configure the Workers CLI

Now that Wrangler is installed, you'll need to give it an API Token for your Cloudflare account.

Run the command wrangler login and Wrangler will ask to automatically open your web browser to log into your Cloudflare account. If you are in an environment that doesn't have a GUI, you can copy and paste the url into a browser and log in.

$ wrangler loginAllow Wrangler to open a page in your browser? [y/n]y💁  Opened a link in your default browser:

Open the browser, log into your account, and click the Authorize Wrangler button. This will send an API Token to Wrangler so it can deploy your scripts to Cloudflare.

4. Generate a new project

Wrangler’s generate subcommand will create a new project from a “starter” template—just a GitHub repo. With no template argument, Wrangler generates projects from the default starter. Let’s generate a new project, called my-worker:

~/ $ wrangler generate my-worker

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

~/ $ cd my-worker~/my-worker $ LICENSE_MIT        index.js           wrangler.tomlLICENSE_APACHE          package.json
~/my-worker $ cat wrangler.tomlname = "my-worker"type = "javascript"account_id = ""workers_dev = trueroute = ""zone_id = ""

Visit the Starters page to see a complete list of our recommended starter templates.

For example, to build a Workers project in TypeScript, you would instead run:

~/ $ wrangler generate my-typescript-worker

To start a project from your own code—rather than a starter—use wrangler init.

5. Write code

With your new project generated, you’re ready to write your own code.

5a. Understanding Hello World

At its heart, a Workers app 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 in to the Workers runtime, which in turn emits a “fetch” event in the isolate where the script is running.

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

Let’s break this down:

  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 us intercept the request in order send back a custom response (in this case, 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

Now that we have a very basic script running on all requests, the next thing you’ll commonly want to be able to do is generate a dynamic response based on the requests the Worker script is receiving. This is often referred to as routing or filtering.

Option 1: Manually filter requests

You can 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.jsaddEventListener("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’s very common to filter requests based on:

  • request.method — e.g. GET or POST.
  • request.url — e.g. filter based on query parameters or the pathname.
  • request.headers — filter based on specific headers.

See a 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, e.g. the region or timezone.

Option 2: Use a template for routing on URL

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

~/ $ wrangler generate my-worker-with-router

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 just 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 transform HTML on the fly, 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 so much more.

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

6. Preview your project

In order to preview our Worker, we're going to need to configure our project by adding our Account ID to our project's wrangler.toml.

Run the command wrangler whoami and copy your Account ID.

$ wrangler whoami👋  You are logged in with an API Token, associated with the email '<Your Email>'!
+----------------------------------+----------------------------------+| Account Name                     | Account ID                       |+----------------------------------+----------------------------------+| Your Account                     | $yourAccountId                   |+----------------------------------+----------------------------------+

Then, open up your project's wrangler.toml and paste it in as the value for the account_id field.

wrangler.tomlname = "my-worker"account_id = "$yourAccountId"

Once you've done that, you’re ready to preview your code. Run the wrangler dev command:

~/my-worker $ wrangler dev💁  watching "./"👂  Listening on

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

7. Configure your project for deployment

To configure your project, we need to fill in a few missing fields in the wrangler.toml file in the root of the generated project. This file contains the information Wrangler needs to connect to the Cloudflare Workers API and publish your code.

You should have already filled in the account_id field in the last step. If you didn't, you can get your Account ID by running wrangler whoami.

$ wrangler whoami👋  You are logged in with an API Token, associated with the email '<Your Email>'!
+----------------------------------+----------------------------------+| Account Name                     | Account ID                       |+----------------------------------+----------------------------------+| Your Account                     | $yourAccountId                   |+----------------------------------+----------------------------------+

Then, paste it into your wrangler.toml as the value for the account_id field.

wrangler.tomlname = "my-worker"account_id = "$yourAccountId"

Let’s also configure the type to "webpack", to tell Wrangler to use Webpack to package your project for deployment. (Learn more about type configuration.)

wrangler.tomlname = "my-worker"account_id = "$yourAccountId"type = "webpack"

By default, this project will deploy to your subdomain. When deploying to a subdomain, the name field will be used as the secondary subdomain for the deployed script, e.g.

(Optional) Configure for deploying to a registered domain

To publish your application on a domain you own, and not a subdomain, you can add a route key to your wrangler.toml.

You can get your zone_id with the following steps:

  1. Log in to your Cloudflare account and select the desired domain.
  2. Select the Overview tab on the navigation bar.
  3. Scroll down until you see both Zone ID on the right.
  4. Click Click to copy below the input.

Wrangler’s environments feature allows us to specify multiple different deploy targets for our application. Let's add a production environment, passing in a zone_id and route:

wrangler.tomlname = "my-worker"account_id = "$yourAccountId"type = "webpack"workers_dev = true
[env.production]# The ID of the domain to deploying tozone_id = "$yourZoneId"
# The route pattern your Workers application will be served atroute = "*"

The route key here is a route pattern, which e.g., 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 (the response comes directly from a Worker), you should enter a placeholder (dummy) AAAA record pointing to 100::, which is the reserved IPv6 discard prefix.

8. Publish your project

With our project configured, it’s time to publish it.

To deploy to our subdomain, we can run:

Publish to $ wrangler publish

(Optional) Publish your project to a registered domain

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

Publish to $ wrangler publish --env production

For more information on environments, check out the Wrangler documentation.

You can also configure a GitHub repo 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.

Where to go next

This is just the beginning of what you can do with Cloudflare Workers. To dive deeper into building meaty projects, check out our Tutorials.