---
title: "Getting Started with Cloudflare Workers"
description: "Need a way to publish application that doesn't consume container or VM technology? Learn how to create and publish an application with Cloudflare Workers in this tutorial!"
canonical: "https://adamtheautomator.com/cloudflare-workers/"
---

# Getting Started with Cloudflare Workers

> Need a way to publish application that doesn't consume container or VM technology? Learn how to create and publish an application with Cloudflare Workers in this tutorial!

Source: https://adamtheautomator.com/cloudflare-workers/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Getting Started with Cloudflare Workers](https://adamtheautomator.com/wp-content/uploads/2021/11/Getting-Started-with-Cloudflare-Workers.jpg)

# Getting Started with Cloudflare Workers

[![](https://secure.gravatar.com/avatar/5f3686e92dbfdc7017ac4ab5cb9abb7de6bdce69362126caf723caffb405f14c?s=192&d=mm&r=g)Kelvin Kipkorir](https://adamtheautomator.com/author/kelvin-kipkorir/)2 November 20216 min. read

Categories: [Cloud](/category/cloud/)

Tags:[CloudFlare](/tag/cloudflare/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Installing and Configuring Cloudflare Workers Wrangler](#installing-and-configuring-cloudflare-workers-wrangler)
*   [Generating a Cloudflare Workers Project](#generating-a-cloudflare-workers-project)
*   [Rendering an HTML Page](#rendering-an-html-page)
*   [Publishing a Serverless Application](#publishing-a-serverless-application)

Are you looking for a solution to deploy a serverless application on a global platform to run as close as possible to the end-user? Let Cloudflare Workers be that solution. Cloudflare Workers is a global content delivery network provider that focuses on the performance and security of your web infrastructure.

In this tutorial, you will learn how to deploy your first serverless application with Cloudflare Workers. Buckle up as you get started with the Cloudflare Workers experience!

## Prerequisites

This tutorial comprises hands-on demonstrations. Be sure you have the following in place to follow along:

*   [Visual Studio Code](https://code.visualstudio.com/download) (VS Code) and this tutorial uses version 1.61.0.
*   [Node Package Manager](https://nodejs.org/en/download/package-manager/) installed and this tutorial uses version 16.8.0.
*   [Cloudflare Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/get-started/) installed and configured, this tutorial uses 1.17.1-rc.
*   A [Cloudflare Workers](https://dash.cloudflare.com/sign-up/workers) account – Note the sub-domain you set upon creating your account.

## **Installing and Configuring Cloudflare Workers Wrangler**

Before you can deploy a serverless application, you need to build one based on a [serverless Framework](https://www.cloudflare.com/learning/serverless/glossary/serverless-and-cloudflare-workers/). How? First, you’ll need to install Wrangler, a command-line tool that manages the building, uploading, and publishing of serverless applications.

1\. Open VS Code from your Desktop, then click on the **Terminal** menu → **New Terminal**, below. Doing so opens a terminal at the bottom part of VS Code’s window.

![Accessing Terminal in VS Code](https://adamtheautomator.com/wp-content/uploads/2021/11/image.png)

Accessing Terminal in VS Code

2\. Next, run the `npm` command below to install (`i`) Cloudflare Wrangler modules (`@cloudflare/wrangler`) in the global home directory (`-g`). The `-g` option eliminates permissions issues that may arise while performing installations.

```powershell
npm i @cloudflare/wrangler -g
```

![Invoking the npm i @cloudflare/wrangler -g command should print out this response.](https://adamtheautomator.com/wp-content/uploads/2021/11/image-1.png)

Invoking the `npm i @cloudflare/wrangler -g` command should print out this response.

3\. Run the command below to confirm you’ve completely installed Wrangler. This command prints out the version of Wrangler installed in your machine.

```powershell
wrangler --version
```

![Checking Wrangler Version Installed](https://adamtheautomator.com/wp-content/uploads/2021/11/image-2.png)

Checking Wrangler Version Installed

4\. Now, run the command below to authenticate your Wrangler installation to Cloudflare Workers. The command opens the Cloudflare login page in your browser.

```powershell
wrangler login
```

5\. Log in to your Cloudflare Workers account, and Cloudflare will provide you with an API token to authenticate the `wrangler` connection to your Cloudflare account. consent.

![Running the Wrangler login Command prompts you with a Cloudflare Login Page for authentication](https://adamtheautomator.com/wp-content/uploads/2021/11/image-3.png)

Running the `Wrangler login` Command prompts you with a Cloudflare Login Page for authentication

6\. Finally, run the command below to print out your credentials, which confirms you’ve successfully configured Cloudflare Workers.

```javascript
 wrangler whoami
```

Below, you can see the command prints out a message, which says you are logged in with a Global API key associated with your email, account name, and account ID.

Note the **Account Name** and **Account ID**, as you’ll use them as credentials later on to publish the project.

![Confirming Cloudflare Workers is Configured Successfully](https://adamtheautomator.com/wp-content/uploads/2021/11/image.jpeg)

Confirming Cloudflare Workers is Configured Successfully

## **Generating a Cloudflare Workers Project**

Now that you’ve set up Cloudflare Workers let’s generate your new Cloudflare Workers project. Cloudflare Workers has [Starter templates](https://developers.cloudflare.com/workers/get-started/quickstarts) that contain reusable code snippets built for developers to get started with when building with Workers.

For this demo, you will use the starter template, which allows you to build a JavaScript-based project on top of Cloudflare Workers.

> _The worker template supports building projects with [webpack](https://developers.cloudflare.com/workers/wrangler/migration/eject-webpack/) since it offers multiple deployment targets that you can set in your webpack configuration. Webpack simplifies the process of adding and managing npm dependencies in your project._

1\. Run the command below to create a folder called `new-worker`, which stores the important worker template’s project files pulled from GitHub `https://github.com/cloudflare/worker-template`.

```bash
# Creates a new folder called new-worker
# Pulls the starter template from GitHub, 
# and places the important project files in the new-worker folder. 
wrangler generate new-worker https://github.com/cloudflare/worker-template

# Change working directory to the new-worker folder
cd new-worker
```

Below, you can see the project’s file structure inside the _~/new-worker_ folder.

![Listing Files and Sub-directories of the new-worker Folder](https://adamtheautomator.com/wp-content/uploads/2021/11/image-4.png)

Listing Files and Sub-directories of the new-worker Folder

2\. Open the _~/new-worker/index.js_ file, which acts as an entry point to manage the application’s modules. Inside the file are [Worker Runtime APIs](https://developers.cloudflare.com/workers/runtime-apis), which are functions running in the browser background to intercept and control how Cloudflare handles network requests from you.

The code below is generated by the starter template, which handles the [fetch event](https://developers.cloudflare.com/workers/runtime-apis/fetch-event) then prints the `Hello World!` message by default as a response. The fetch event is the incoming requests from a client to your application,

```javascript
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
// this script tells FetchEvent  worker  how to respond to any incoming fetch request.
// the Worker script then returns a response to the user.
})

async function handleRequest(request) 
// this function takes an event and context object as input and returns a string.
// the async function takes request provided as the parameter. 
// The Worker then receives HTTP requests and responds automatically.
{
  // Prints a plain text that says Hello World!
  return new Response('Hello World!', { 
    headers: { 'content-type': 'text/plain' },
  })
}
```

3\. Finally, run the command below to test that the `return new Response` function in the _index.js_ file prints out the expected response.

```bash
wrangler preview
```

After building your application, the command automatically opens up a new tab on your browser, as shown below, and displays the response.

![Testing if the preview Function Works](https://adamtheautomator.com/wp-content/uploads/2021/11/image-5.png)

Testing if the `preview` Function Works

## **Rendering an HTML Page**

Now that the basics of creating a function are out of the way let’s create an HTML template that mimics and displays as a web page instead of just plain text.

1\. Create a new file with a name you prefer in the working directory, but for this example, the file is named _worker.js. C_opy/paste the code below to the _worker.js_ file.

The code below creates a worker that mimics a web page that prints the “Hello there 👋! You’re connected to Cloudflare Workers” message.

```javascript
const worker = `
//html code to create the new webpage.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Hello!</title>
    <link rel="stylesheet" href="https://unpkg.com/modern-css-reset/dist/reset.min.css" />
    <style>
    // styling for the new web page.
      body {
        background: #eee;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 100vh;
        font-family: sans-serif;
      }
      div.container {
        background: #fff;
        border-radius: 1rem;
        padding: 4rem;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1> Hello there 👋! You're connected to Cloudflare Workers </h1>
    </div>
  </body>
</html> `

//This grants access to index.js file when the user calls the worker function.
export default worker 
```

2\. Next, open the _~/new-worker/index.js_ file, then replace the content with the code below.

The code below imports the worker function from the _worker.js_ file you created in step two to be accessed here in the _index.js_ file.

```javascript
import worker from './worker'
// This imports the worker file, goes ahead to take the HTML you created earlier,
// and make it your new response.
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
//the addEventListener function listens for a fetch request from the worker
//the event.respondWith() method allows you to provide a response to the fetch.
})

async function handleRequest(request) {
  return new Response(worker, {
    headers: { 'content-type': 'text/html' },
		// The async function recieves the new request and 
		// returns new custom response of text/html type.
  })
}
```

3\. Finally, refresh your browser, and you will see that the body is rendering as an actual HTML page.

More importantly, the worker script (_worker.js_) returns the content you anticipated as the response, which is the **Hello there 👋! You’re connected to Cloudflare Workers** message.

![Rendering an HTML Page](https://adamtheautomator.com/wp-content/uploads/2021/11/image-6.png)

Rendering an HTML Page

## **Publishing a Serverless Application**

Since you’ve confirmed that rendering an HTML page works on your local machine, it’s finally time to deploy a serverless application. But first, you’ll configure the _~/new-worker/wrangler.toml_ file to define the application’s settings and parameters.

Related:[How to Deploy a Website with Cloudflare Pages](https://adamtheautomator.com/cloudflare-pages/)

> _Unlike other cloud computing platforms, Cloudflare doesn’t [consume container](https://developers.cloudflare.com/workers/learning/how-workers-works) or virtual machine technology. Instead, Cloudflare Workers runs on [V8: Isolates](https://v8.dev), a JavaScript engine developed for Google Chrome._

1\. Open the _~/new-worker/wrangler.toml_ file, and make the following changes in the file’s content:

*   Change the project type from `JavaScript` to `Webpack`. This change helps import and manage the deployment of freshly-bundled Cloudflare Workers scripts and dependencies within the project.
*   Put the Account ID you noted in step 6 of the “Installing and Configuring Cloudflare Workers Wrangler CLI” section to the `account_id` placeholder.
*   The last two fields (`route` and `zone_id`) are particular to deploying your project. They tell Wrangler that you want to deploy a serverless function to a subdomain in a specific [zoneID](https://developers.cloudflare.com/workers/get-started/guide).

For now, leave them blank because you will not use the zoneID feature in your project and proceed with publication.

```javascript
name = "new-worker"
type = "webpack"

account_id = "81f630695fef040a80b2e2f8e4f5882d"
workers_dev = true
route = ""
zone_id = ""
```

2\. Run the `dev` command, a Wrangler built-in worker script, to visualize how your project will look in the production environment. The command automatically opens up a new URL on your browser and shows the response you configured in the _~/new-worker/worker.js_ file.

```bash
wrangler dev
```

3\. Now run the [`wrangler publish`](https://developers.cloudflare.com/workers/wrangler/commands/#publish) command below to build, upload and publish your function on _workers.dev_, the domain created earlier when you signed up for the Cloudflare account.

```bash
wrangler publish
```

Note the new URL to access your application as follows. Replace `project-name` with your project’s name and `sub-domain` with the subdomain you chose when you created your Cloudflare account.

```powershell
project-name.sub-domain.workers.dev

For example: new-worker.kevin-cfworker.workers.dev
```

Open the link in your browser, as shown below, to access your serverless application in the production environment.

Below, you can see the page looks the same as it did locally in step three of the “Rendering an HTML Page” section. If you see the **Hello there 👋! You’re connected to Cloudflare Workers** message on your browser, and then you’re all set!

![Accessing the Serverless Application in the Production Environment](https://adamtheautomator.com/wp-content/uploads/2021/11/image-1.jpeg)

Accessing the Serverless Application in the Production Environment

# Conclusion

In this tutorial, you’ve built and deployed a serverless application to Cloudflare Workers. Throughout the process of building the application, you’ve learned how to configure the application settings and responses to your liking.

As a next step, why not look into implementing VPN tunneling via Cloudflare WARP client to secure the network traffic of end-user within the network?

Related:[Getting Started with Cloudflare Warp](https://adamtheautomator.com/cloudflare-warp/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fcloudflare-workers%2F&text=Getting%20Started%20with%20Cloudflare%20Workers)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fcloudflare-workers%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fcloudflare-workers%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2021/09/How-to-Setup-CloudFlare-Dynamic-DNS-.jpg)

### [How to Setup Cloudflare Dynamic DNS](/cloudflare-dynamic-dns/)

Keep your DNS record updated using Cloudflare's application programming interface (API) and learn how to set up Cloudflare Dynamic DNS via PowerShell and Cloudflare's API!

![](https://adamtheautomator.com/wp-content/uploads/2021/09/How-to-Deploy-a-Website-with-Cloudflare-Pages.jpg)

### [Discover Cloudflare Pages and Skyrocket Deployment of your Website](/cloudflare-pages/)

Learn how to deploy a static website to Cloudflare Pages! Cloudflare Pages enables the serving of static websites from hundreds of locations, close to the client, around the world without a traditional hosting server.

![](https://adamtheautomator.com/wp-content/uploads/2019/07/5d238ae5c824b514689ea66e.jpg)

### [Create & Host Azure Static Websites with Ease](/azure-static-website/)

Build and host an Azure static website with HTTP and HTTPS support using HTML, CSS, and JavaScript.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
