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

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

4. Write code

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

4a. 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.

4b. 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.

4c. 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 HTMLRewriter to parse and transform HTML on the fly, use the Cache to retrieve data from and put data into from 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.

5. Preview your project

When you’re ready to preview your code, run Wrangler’s preview command:

~/my-worker $ wrangler preview --watch

This command will build your project, upload it to a unique URL, and open a tab in your browser to view it. This allows you to quickly test your project running on the actual Workers runtime, and optionally, even share it with others too.

The --watch flag tells Wrangler to watch your Workers project directory for changes, and will automatically update the preview tab live with the latest URL.

6. Configure your project for deployment

In order to publish your Workers project on Cloudflare’s global cloud network, you’ll need to configure Wrangler using details from your Workers account.

Specifically you’ll need to obtain:

  • Account ID

  • API token (recommended), or both email and Global API Key.

If deploying on a free subdomain, that’s it. If you’re deploying onto your own domain, you’ll additionally need to configure the project with:

  • Zone ID

6a. Obtaining your Account ID (and Zone ID)

For domains, you will just need the Account ID:

  1. Log in to your Cloudflare account and select Workers.
  2. On the right, look for Account ID and click Click to copy below the input.

Registered domains

For domains that you have registered on Cloudflare, you need both IDs:

  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 and *Account ID on the right.
  4. Click Click to copy below the input to each.

6b. Obtaining your API token or Global API key

  1. Continuing, also on the right side, click Get your API token.
  2. You’ll be taken to your Profile page.
  3. Click Create token.
  4. Under the API token templates section, find the Edit Cloudflare Workers template and click Use template.
  5. Fill out the rest of the fields and then click Continue to summary, where you can click Create Token and issue your token for use.

Option 2: Obtaining your Global API Key

  1. Continuing, also on the right side, click Get your API token.
  2. You’ll be taken to your Profile page.
  3. Scroll to API Keys, and click View to copy your Global API Key.*

6c. Configuring Wrangler with your credentials

Set up your default credentials on your local machine with wrangler config. This is an interactive command that will prompt you for your API token:

$ wrangler configEnter API token:superlongapitoken

Use the --api-key flag to instead configure with email and global API key:

$ wrangler config --api-keyEnter email:testuser@example.comEnter global API key:superlongapikey

You can also use environment variables to configure these authentication credentials.

6d. Configuring your project

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.

For now, fill in just the account_id field with the value found in your dashboard.

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"

Finally, we need to tell Wrangler where we want to deploy our project.

Configure for deploying to

With the workers_dev key in wrangler.toml set to true, Wrangler will publish your project to your subdomain.

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

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.

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.

7. Publish your project

With our project configured, it’s time to publish it. The way we’ve configured it we have two deploy targets we can publish to.

To deploy to our subdomain, we can run:

Publish to $ wrangler publish

To deploy to our “production” environment we set in our wrangler.toml, 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.