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 workers.dev subdomain, you’ll need to sign up for a Cloudflare Workers account.
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 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/wranglerThen run wrangler --version to confirm that the installation was successful:
$ wrangler --versionwrangler v1.10.33. 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-workerWrangler 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 $ lsCODE_OF_CONDUCT.md LICENSE_MIT index.js wrangler.tomlLICENSE_APACHE README.md 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 https://github.com/EverlastingBugstopper/worker-typescript-templateTo 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:
- An event listener that listens for
FetchEvents, and - 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:
An event listener for the
FetchEventtells the script to listen for any request coming to your Worker. The event handler is passed theeventobject, which includesevent.request, aRequestobject which is a representation of the HTTP request that triggered the FetchEvent.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
FetchEventhandler typically culminates in a call to the method.respondWith()with either aResponseorPromise<Response>that determines the response.The
FetchEventobject 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 do 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.GETorPOST.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 https://github.com/cloudflare/worker-template-routerThis 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 --watchThis 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 workers.dev 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)
workers.dev
For workers.dev domains, you will just need the Account ID:
- Log in to your Cloudflare account and select Workers.
- 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:
- Log in to your Cloudflare account and select the desired domain.
- Select the Overview tab on the navigation bar.
- Scroll down until you see both Zone ID and *Account ID on the right.
- Click Click to copy below the input to each.
6b. Obtaining your API token or Global API key
Option 1: Obtaining your API token (recommended)
- Continuing, also on the right side, click Get your API token.
- You’ll be taken to your Profile page.
- Click Create token.
- Under the API token templates section, find the Edit Cloudflare Workers template and click Use template.
- 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
- Continuing, also on the right side, click Get your API token.
- You’ll be taken to your Profile page.
- 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:superlongapitokenUse the --api-key flag to instead configure with email and global API key:
$ wrangler config --api-keyEnter email:testuser@example.comEnter global API key:superlongapikeyYou 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 workers.dev
With the workers_dev key in wrangler.toml set to true, Wrangler will publish your project to your workers.dev subdomain.
wrangler.tomlname = "my-worker"account_id = "$yourAccountId"type = "webpack"workers_dev = trueWhen deploying to a workers.dev subdomain, the name field will be used as the secondary subdomain for the deployed script, e.g. my-worker.my-subdomain.workers.dev.
(Optional) Configure for deploying to a registered domain
To publish your application on a domain you own, and not a workers.dev 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 = "example.com/*"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 workers.dev subdomain, we can run:
Publish to workers.dev~/my-worker $ wrangler publishTo deploy to our “production” environment we set in our wrangler.toml, we can pass the --env flag to the command:
Publish to example.com~/my-worker $ wrangler publish --env productionFor 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.
