Cloudflare worker: Run code on the edge

satish1v
3 min readAug 22, 2022
Photo by Michael Dziedzic on Unsplash

Cloudflare's Cloudflare Worker is a serverless platform, but it differs significantly from those offered by other well-known providers. The distinction requires some background knowledge to be understood.

History

Cloudflare was one of the first companies to offer CDN and DNS services in over 200 locations. They have a data center in each of 200 locations, while AWS has one in just under 100. Meanwhile, Cloudflare's network grows. Cloudflare's workers can now run code on a serverless platform.

The Cloudflare worker is different because when you deploy code, it doesn't just run the code in one place like other serverless systems. Instead, your code is run all over the world. If you deploy the code, it will automatically run on all 200 data centers. So customers will be served from the location closest to them with as little delay as possible.

How do you deploy to Cloudflare? Install Wrangler using NPM.

Getting Started

Wrangler is the developer tool for making the development/Testing and deployment cycle more straightforward.

If you are on a Windows PC, Fire up the Powershell and start with the command below; the same will also work in Bash.

To install Wrangler :

npm install -g wrangler 

This will install Wrangler on the computer, and you can now log in using

wrangler login

This will help us push the code to production with appropriate credentials

Now that we have logged in, Its time to start our code, and you start the project using the following command

wrangler init <Project_name>

Replace the project name with anything you like. You will be prompted with the following questions.

In your terminal, you will be asked:

  1. Would you like to use git to manage this Worker? (y/n) Indicate y.
  2. Would you like to use TypeScript? (y/n) Indicate y to continue with JavaScript for this guide.
  3. No package.json found. Would you like to create one? (y/n) Indicate y.
  4. Would you like to create a Worker at <YOUR_WORKER>\src\index.ts? Indicate y.

This will create the files required to write a function. As this is a getting started post, let's only concentrate on the Index.ts.

You can run the application, which will run at http://localhost:8787. The output should be

Hello World

But that's not very interesting. Let's make it more fun by testing Cloudflare's claim that they serve requests from the region closest to the user. So I'll change the code to send the request back.

This code handles the incoming request and returns its properties so you can process them. That way, you can personalize the user's experience by sending them content that is only accessible in their geographical region.

Cloudflare has added some exciting properties to the HTTP request object in the browser's output.

More info

--

--