CodeX
Published in

CodeX

My First Cloudflare Worker

In the tech world, there’s a bunch of innovators that are creating the next innovation. One of those companies is Cloudflare, the CDN provider doing a lot of cool stuff, including today’s topic, their Workers. Cloudflare Workers are serverless apps deployed through their local network. No matter where you are, it will be up and running within seconds of publishing it.

Examples of these workers range from a simple HTML page to providing authorization to users, creating a cached API and, getting creative with a data-driven app using PostgreSQL, which is good news for me since I’m a PostgreSQL fan. My first worker (I left the name first-worker promising myself to do more) is a simple HTML page that will guess the city you’re visiting the page.

Installing Wrangler

To create a worker, you need to install the Wrangler CLI first. First, create a Cloudflare Worker account.

npm install -g @cloudflare/wrangler

After the account it’s created, you can proceed to install Wrangler.

wrangler login

Log in to your account with the above command.

wrangler generate first-worker

Now that we got the Wrangler CLI, it’s time to create the first project.

Coding JavaScript

Now, time to get to the fun part! The easiest way to get started is with a Quickstart. However, if you’d like to accept the challenge to start with your code, enter wrangler init.

wrangler generate my-app https://github.com/cloudflare/worker-template

Since I’m coding my Worker in JavaScript, I entered the command to get a template. So I’m starting this worker with some of the code I need to achieve what I want.

First, we got the index.js file, which imports the template variable from the template file on the first line.

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

Workers support two kinds of events, fetch and schedule. For this project, we need to call fetch.

async function handleRequest(request) {  
return new Response(template(request.cf), { headers: { 'content-type': 'text/html' },
})
}

The above code is the event handling function. It’s pretty much straightforward JavaScript event handling. But, there’s a detail I’d like to concentrate on, that is Response(template(request.cf). Workers have a feature that will provide you with the information iterated just by invoking request.cf in your code.

So let’s go to the template file. Before providing the entire code for the file, I’d like to share this exact line of code:

<h1>Hello there! You’re connecting from ${cf.city}</h1></br>

We used a back-tick delimiter to iterate the city from the IP Address you’re visiting.

Here’s the full template code:

Publish Worker

First, let’s ensure we got everything we need on the wrangler.toml file.

name = “first-worker”
type = “webpack”
account_id = “account_id”
workers_dev = true
[env.production]
workers_dev = false
route = “https://hello-worker.norbertosantiago.com/"
zone_id = “zone_id”
compatibility_date = “2022–01–15”

First, we can see the page in the dev environment. You can keep playing with the worker you created. And keep making changes and share the dev page when you make changes for fellow developers to see. However, there’s a catch with Cloudflare. You’ll need to buy a domain from themselves to be able to publish your worker. The good thing is, it’s a lower price than most providers, and you’ll receive the extra security, performance, and perks like this for that low price.

If you decide to get the domain, add the zone_id, the route is the URL you want to give the worker with your domain, and the following lines of code:

[env.production]
workers_dev = false

Once you have everything set up in the wrangler.toml file, enter the following command line to publish:

wrangler publish --env production

Very Important: Make sure to add the CNAME to your domain. In my case, the added CNAME is hello-worker.

Now, let’s go ahead and test the worker using a VPN.

VPN connected in Japan.
Kon’nichiwa, Tōkyō ni imasu.

Let’s move to another continent.

VPN connected in Costa Rica.
Hola a usted allá en San José.

So this is it, my first serverless app is live at https://hello-worker.norbertosantiago.com/. Hope you learned something new, and let me know which city did Cloudflare recognized when you entered the site.

Happy Serverless Coding!

Summary:

  1. Introduction to Cloudflare Workers.
  2. Install Wrangler CLI
  3. Code in JavaScript
  4. Publish Worker

Reference:

  1. Cloudflare Workers Documentation

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store