Why and How to use Cloudflare Workers Explained with Sample Code

Cloudflare workers can help you to make changes to your request or response on the fly at the countless global CDN edges of Cloudflare without touching your origin server.

Cloudflare workers work like magic. It sits between your server and Cloudflare CDN POPs, catching every request before it passes the same to the Cloudflare edge servers to either pull it from the origin server or serve it from your nearest Cloudflare CDN pop. This gives a unique advantage to Cloudflare workers which is not easily possible in any other way. You can do some crazy magical things with Cloudflare workers, without increasing your server load or the response time from your origin servers.

Today in this article we will talk about what is Cloudflare workers, why you should care, how to use Cloudflare workers, and then finally will show a sample code that we often use on many of our client sites to make redirections, add security headers, etc. Please note that though the sample code will show you how to make easy redirections and add security headers using Cloudflare workers (which might sound basic to you), you can do so much more with Cloudflare workers. We will also provide some example code via GitHub Gists of some other possible use cases. But then again the limitation of Cloudflare Workers is simply your imagination.

What is Cloudflare Worker & Why should we care?

Before we dig deeper into how to use Cloudflare workers, it is very important to know what they are and why should you care. Think of Cloudflare workers as a middleman between your origin server and other Cloudflare services like caching, CDN, etc. If you have set up a Cloudflare worker, each time someone tries to access your website, the request will first hit Cloudflare DNS servers as to fully use Cloudflare services you must need to use Cloudflare as your DNS provider (which is the best DNS provider in our opinion) and we all know it.

Now before sending the response to you with the origin server IPs and other details, if you have set up some logic inside your Cloudflare workers, the worker will catch your request and process it. After that, the worker will decide what response to send and will send you the response accordingly. Now the best part about Cloudflare workers is that when you deploy your worker code, instead of it getting deployed on a server located at a specific location, it gets deployed all around the world in every Cloudflare edge server there is all around the globe.

What this means is that if you have a website or business which gets accessed from all around the world, when a user tries to access your website, the Cloudflare DNS server nearest to you is going to process that DNS request and at the same time your worker code will be executed on that same edge which is nearest to you, reducing your latency and response time to the lowest possible level.

How to setup Cloudflare Workers

Now as you know what Cloudflare workers are and why you should care, let's talk about how to set them up, as it will take less than 2 minutes to set up and deploy your Cloudflare workers. Let's take a look at the step-by-step guide on how to enable and deploy Cloudflare workers on your Cloudflare account.

  1. Login to your Cloudflare Dashboard
  2. Click on the Zone name for which you want to set up the Workers
  3. From the top menus select the option named "Workers"
  4. Click on the "Manage Workers" button
  5. Select a slug that will the part of your Cloudflare Workers URL
  6. Write your first Cloudflare Worker code in any of your favorite languages (JavaScript, Rust, C, C++, etc.)
  7. Test your Worker code on that very same page where you wrote your code
  8. Deploy your worker code all around the world in every edge server Cloudflare has to offer
  9. Come back to your Cloudflare Dashboard, click on "Workers" again and this time click on the "Add Route" button to let Cloudflare know for which of your zone you want the Worker to intercept the requests. You can also use URL expressions while setting up the route.

Besides the approach mentioned above, if you want you can also use Cloudflare Workers CLI to set up your workers. Now, let's take a look at some screenshots of the above step-by-step approach mentioned above just so you have a much clearer idea about the steps.

Cloudflare Login Page
Login to your Cloudflare Dashboard
Select Cloudflare Zone
Select your Zone
Go to Cloudflare Worker tab
Go to the Workers tab
Go to Manage Workers section
Click on Manage Workers
Setup Worker Subdomain
Set up your Worker subdomain
Select Worker Plan
Select the plan
Create Cloudflare Worker
Click on Create Workers
Write worker code and deploy it
Write your worker code, test it & deploy it
Add Cloudflare Worker Route
Add route to your worker

Writing a Cloudflare Workers Code

As stated earlier, the sole goal of Cloudflare workers is to give you the ability to add logical checks before a user gets a response from your server or Cloudflare CDN edges, so that you can write your own logic and Cloudflare will make sure they get implemented on each and every single requests. Now keeping that in mind, let's write our first Cloudflare workers code to add redirections if the request is coming from a hostname other than what we allow and at the same time if the user is visiting the website with the correct URL, we will add some extra security headers to the request.

The Problem We’re Trying to Solve

Imagine you have a domain called example.com and the site is accessible via https://www.example.com. Now you also have example.netexample.orgexample.ussameexample.com etc. We know it's a lot of domains and may sound farfetched, but in reality, it is not that uncommon, as many companies prefer to hold multiple versions of their brand names but want them to be redirected to the same website https://www.example.com when users are trying to access their other version of the brand domains. Also, let's imagine that the website is hosted on a cPanel server which is accessed via https://example.com:2083/ so basically while accessing the cPanel we are not using WWW before our domain name.

Also at the same time, you might want to add some very important security headers like X-Frame-OptionsContent-Security-PolicyX-XSS-Protection to the final response of https://example.com when it is loaded.

The Traditional Approach

Traditionally you would add these redirection rules and security headers in your server configuration file like nginx.conf or .htaccess which is completely understandable. But the problem with this approach is that if your server is physically located in the USA and someone close to your server is making the request, the response is gonna be fast.

But if someone from India is visiting let's say http://www.example.com or https://sameexample.org then first your DNS provider will get the IP of sameexample.com then the server will reply saying it's been redirected. Then the reply will come back to you and again will send a new request to the redirected URL. This is going to be super slow and each redirection will take quite a lot of time and not to mention the extra latency due to the physical distance between the user and the origin server.

Also, this can be really challenging as you might need to write multiple rules at the server level to check for each domain and also to check the cPanel URL structure to handle that differently. Not to mention this will add much repetitive code in your server config which will not only make it harder to read, but also prone to easy mistakes in the future.

Solving the Problem Using Cloudflare Workers

As explained before, the best part of Cloudflare workers is that when you deploy your code, it gets deployed to every server Cloudflare has on every location on earth. So, this time when you make the request from India, the request will not travel all the way to the USA, and instead, your nearest POP will catch the request and reply saying "Hey 👋, the URL you are trying to access has been redirected to https://example.com so your browser will quickly catch it and send a new request to the correct URL https://example.com.

This makes the redirections super fast all around the world and can be super helpful if you have a global client base or viewership as it will be fast all around the world, as explained before. Also if your website gets less than 100,000 Requests/Day then Cloudflare Worker is completely free. Checkout Cloudflare Worker Plans:

Cloudflare Workers Paid Plan Details

Let’s See How to Write Code for Cloudflare Workers

You can write Cloudflare Workers code using JavaScript, Rust, C, or C++. Today in this sample code we are going to use JavaScript to write our Cloudflare workers code as JavaScript is a super-powerful, versatile, and popular language. If you have experience writing Node JS code, you will not face any issues writing Cloudflare Workers code as it uses Node JS for its workers. In case you don't have much experience with writing code in Node JS, but you know JavaScript, you can check the awesome developer documentation provided by Cloudflare to see the possible use cases and understand different syntaxes to write Cloudflare workers. Enough talk, let's see the code.

/**
 * CloudFlare Worker to handle each request
 * and based on the given condition either redirect it to 
 * the proper URL
 * OR add the security headers in case of Status 200
 * @author Acnam Infotech
 * @explanation https://acnam.com/why-and-how-to-use-cloudflare-workers-explained-with-sample-code/
 */
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  // Convert the request to a mutable URL
  const requestURL = new URL(request.url)

  // Check if the website is using correct hostname, protocol or using a port
  // which should not be redirected
  if(
    (
      requestURL.hostname === 'www.example.com' && 
      requestURL.protocol === 'https:'
    ) || 
    (
      requestURL.hostname === 'example.com' &&
      requestURL.protocol === 'https:' &&
      requestURL.port === '2083'
    )
  ) {
    // No need to redirect the URL. Just add the necessary Security Headers
    let response = await fetch(request)

    // Make the headers mutable by re-constructing the Response.
    response = new Response(response.body, response)

    // Add the security headers we want to add to our response
    response.headers.append('X-Frame-Options', 'DENY')
    response.headers.append('Content-Security-Policy', 'block-all-mixed-content')
    response.headers.append('X-XSS-Protection', '1; mode=block')

    // Return the response
    return response
  } else {
    // We need to redirect the URL to the correct hostname
    // Have to redirect the URL to the proper hostname and protocol
    requestURL.hostname = 'www.example.com'
    requestURL.protocol = 'https:'

    // Make the redirect
    return Response.redirect(requestURL, 301)
  }
}

That above block of code sitting in your Cloudflare workers will intercept every request and check if the user is correctly visiting https://www.example.com or https://www.example.com/whatever/. If there is any mismatch like the user is accessing the site via HTTP without using HTTPS or trying to access the website without WWW or accessing a different TLD domain, whatever the case may be, Cloudflare worker will redirect the request to the correct URL at the local CDN edge level without even needing to hit your origin server.

Also, if the user is trying to access cPanel with its unique URL structure like https://example.com:2083/, though the URL doesn't have WWW, our above worker code will run it through the logic we wrote and as it will pass, the worker will not redirect that URL stream.

Now if the user is visiting the correct URL, the Cloudflare Worker is going to fetch the URL internally, add extra security headers to the response and pass it to the user who has requested that URL. All of these with a few lines of code which will work across multiple zones you have on your website.

A Few Things to Note

There are a few things to note before you jump onto using Cloudflare workers. All of these gotchas are already mentioned in Cloudflare workers docs but still, we will briefly mention them here to ensure you understand them.

  • As Cloudflare workers sit before Cloudflare CDN and other services, both your cache and un-cache requests will be counted towards Cloudflare workers usage. But for a normal traffic website, it is hard to get past 100,000 requests/day. But if you need more requests, Cloudflare worker pricing is super cheap, so it won't break the bank.
  • All the routes that you want Cloudflare workers to handle but be added as a zone in your Cloudflare account and the A record for your main domain and the sub-domains like WWW and others need to be orange and proxied via Cloudflare. For any A or CNAME records that are not proxied via Cloudflare DNS (has the orange Cloudflare icon enabled), Cloudflare workers can't intercept them and run your logic on the requests.
  • You cannot add multiple workers to the same URL route configuration. One route URL configuration can have only one worker associated with it. But you can have different workers for different route URL structures.
  • If you write a Cloudflare Worker in one zone, but you want to implement the same logic to other zones you have, there is no need to rewrite the same worker for each zone. When you go to the other zone's workers section, simply click on "Add a route" and add your URL structure, you will see the worker you have created is already there in the drop-down. This is because all Cloudflare workers have global scope and are not specific to each zone.
    So, for the above example we can create the worker inside example.com but then use the same worker for all other brand domains we have. We simply just need to add a route for those other zones and point it toward this worker we wrote.

Other Use Cases of Cloudflare Workers

The redirection and security header addition use case which was mentioned above is just the tip of the huge Cloudflare workers iceberg. You can do so many more things with Cloudflare workers. We would highly recommend you to check out this Cloudflare workers template GitHub directory to see many other possible use cases of how you can use Cloudflare workers in your project. Here you will find many example templates for use cases like AB testing, adding auth to the header, bulk redirects, cache API, sending raw HTML, sending raw JSON, and many more things. Highly recommend you check out the GitHub directory. If you want to see Cloudflare workers in action for some exotic use cases, please watch the YouTube video below.

Conclusion

Cloudflare workers are truly a magical thing allowing users to add countless logic and do countless things to the requests and responses without hitting the origin server. Also thanks to the free tier it can be deployed for free on many small to medium-traffic websites. Even after that, the pricing of Cloudflare workers is so low that any team can easily use them. There is even more to Cloudflare workers that we have mentioned above like using Cloudflare KV, a NoSQL key-value database by Cloudflare that you can hook into your worker to code to store data at Cloudflare edge. But this feature is only available in the Paid plan. Cloudflare workers is like the sea and in this article, we just covered a few grains of sand maybe.

Let us know what do you think about Cloudflare workers? Do you use them in your projects? Do you have any other possible use case examples in your GitHub Gist? Feel free to share them and continue the discussion in the comment section. 🙂

Share your comment

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


Ready to have a worry free website experience?