Categories
Tutorial

Cloudflare Workers Tutorial Part-2: Basic Setup

In this section, we will do an initial setup of Cloudflare Workers for your domain. A Hello World Worker and a basic introduction to the environment.

Initial Setup

Prerequisites

1. Your domain name must be on Cloudflare DNS service. (It is free).

2. Enable Proxy for your domain on which you want to setup Cloudflare Workers as shown in the image below. For this tutorial, I will use techtorrent.org as a sandbox domain name.

Enable Cloudflare Proxy

Basic Setup

1. Go to Workers and then click on Manage Workers

Manage Workers

It will redirect to the Workers page. Then click on Create a Worker button.

It will open a quick edit window for the Worker script. It provides all the features of a browser built-in and you can test your script very quickly. You can also set HTTP methods such as GET, POST etcetera.

Workers quick edit window

On the left side of the window, you will get an inbuilt JavaScript editor where you can update the Worker code. In this tutorial, all the code will be for the Worker.

As you can see in the window I named my Worker tutorial.

The code in the above image will be there already. Take a quick look around and see what else is there.

In case the code is not there, don’t worry. Just keep it as it is for now. (The code is at the end of the article in case you can’t sleep.)

2. Click on Save and Deploy button at the bottom.

3. Go back to your domain’s management page.

4. Click on Workers and then click on Add route

Add route for worker.

A route is a URL on which the Cloudflare Worker will execute. It also supports regex like structure.

For this tutorial, I want to execute Workers on each request no matter what path it is.

Add route

I will add techtorrent.org/* and select worker I created before from the Worker dropdown.

Awesome! The basic setup is completed. Now, if you visit your site in the browser, you will see hello world on the site.

hello world example output

This response came from Cloudflare Worker that we wrote in this tutorial.

Hello World Code

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  return new Response('hello world', {status: 200})
}

This was it for part-2 Setup Cloudflare Workers out of 4 parts. Check out part-3 & part-4 for advanced code snippets.

Leave a Reply

Your email address will not be published. Required fields are marked *