Cloudflare Workers Review


Download PDF

Share


The news that Cloudflare Workers recently exited beta and became available for general use caused a lot of chatter and excitement on the internet. Workers allow you to deploy JavaScript directly onto the Cloudflare Edge that is fired on every request before being passed on to your origins server.

The technology has been hotly anticipated since it was first announced in a blog post back in September 2017. Interest in what functionality would be available and how we can expect to utilize it has steadily increased with each teaser and nugget of information released by the Cloudflare team.

We are strong advocates of the Cloudflare service here at Leader Internet and previously discussed what Cloudflare does for PageSpeed on websites while making them secure.

We applied to be part of the Worker Beta when it was first announced and received early access ago a couple of months ago. Since then, we’ve been experimenting with the features and had conversations with members of the Workers team to provide feedback and improve our knowledge of what it can do.

The technology is so new it’s hard to find a good Cloudflare Workers Review but we are perfectly placed to offer our opinions as early access users.

Contents

What Are Cloudflare Workers

Cloudflare Workers are JavaScript snippers that are deployed on the edge. They are based on the principle of Service Workers whereby requests can be intercepted and modified. The difference is that Service Workers run in the background of the user's browser while Cloudflare Workers run on Cloudflares global infrastructure.

cloudflare-workers-review.pngImage courtesy of Cloudflare.com

background

Developers have always had two places to deploy their code. The client side or the server side. Static code is generally done in the browser and any dynamic responses need to go all the way to a server.

The natural evolution of this then is Workers, the ability to add functionality between servers and clients, directly onto the Cloudflare Network AND have the freedom to customize it to your needs. In other words, JavaScript on the Edge.

Use Cases

The Workers docs lay out some of the uses cases proposed by the creators such as:

  • A/B testing
  • Load Balancing
  • Rendering HTML from dynamic content
  • Dynamically respond to requests direct from the edge
  • Sanitize data before it enters the backend
  • Deploy fast fixes to a site


Add interactivity to static sites

When we first heard about Workers we immediately started investigating could the tech be used to add interactivity to static websites, which are an emerging Trend In Web Development due to of the speed and simplicity they offer.

For anyone operating static sites, 99% of the time, things are fine but there will always be that one occasion when some computation is needed instead of sending back a static response.

Until now the most common option would have been to add some JavaScript that fires after page load and alters the UI or fetches data from an endpoint. The down side of this is that users see the page shifting after it loads. A common hack on top of this is to hide the page content until all JS has processed but this only serves to increase the perceived loading time.

Enter Cloudflare Workers. Developers can handle these requests and respond dynamically before they even reach the server. There is no post load computation and Workers respond so fast in the background, the transition is unnoticeable.

How It Works

First, let’s analyse how Cloudflare handles a request without Workers:

Without Workers

  1. A user visits mysite.com
  2. Cloudflare handles the request and filters out any unwanted traffic before forwarding it onto your origin server
  3. Your server generates the page and sends it back to Cloudflare
  4. Cloudflare applies their performance optimizations and sends the response back to the user's browser

Now compare to what happens with Workers:

With Workers

  1. A user visits mysite.com
  2. Cloudflare handles the request and fires whatever JavaScript is specified in worker code.
  3. Only if a Worker cannot send a response back to the user's browser, the request will be passed onto the origin server.

What this means is that you can put JavaScript at the very front line of your infrastructure that handles each request and responds accordingly. To do this, log in to the Cloudflare dashboard, click on the worker's tab and enter your JavaScript code. Specify the route it should be fired on and click save to immediately push your Worker live to Cloudflare’s global CDN. Every page load of the specific path will now fire this JavaScript. It’s that simple.

cloudflare-workers-dashboard.pngCloudflare Workers Dashboard

Workers can also be deployed via the API but no need to complicate things at first. You can make changes directly within the dashboard and test them using the preview panel.

Warning
Workers go live immediately so make sure not to activate them site wide. Setup a test page or experiment one for a low traffic URL. This can be specified in the routes panel of the worker.

Our Experiments

To test the functionality of Workers, we set up a few experiments.

IP redirection

One of our clients has a site that takes traffic from two countries - UK and Ireland. They had a problem that everyone was landing on the UK version, which is no good for Irish customers because the prices are in pounds instead of euros.

When reviewing the Cloudflare Workers docs, we realized it’s possible to read request headers in the worker code. Furthermore, Cloudflare detects the origin IP of the incoming request and appends a two-letter country code.

This allowed us to write a simple worker that checks the country code and then redirect to the appropriate version if it exists.

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

async function fetchAndApply(request) {

    const country = request.headers.get('Cf-Ipcountry').toLowerCase() 
    let url = new URL(request.url)

    const target_url = 'https://'+url.hostname+'/'+country
    const target_url_response = await fetch(target_url)

    if(target_url_response.status == 200) {
        return new Response('', {
          status: 302,
          headers: {
            'Location': target_url
          }
        })     
    } else {
        return response
    }
}


Protecting Test Sites

When building websites locally we like to move them to a test environment first instead of going straight to production. These need to be password protected so customers and competitors don’t see the content before it’s ready. They also need to be inaccessible to bots so google doesn’t crawl them and issue a penalty for duplicate content which can require all srots of SEO tricks and fixes to rectify

The most common approach is putting them behind a firewall or HTTP Basic Authentication but both of these options require server level changes, which take time and can be beyond the skills of some developers. Even if someone has the knowledge, bashing around on the terminal is an unpleasant and error-ridden procedure. The site content is not super sensetive so we just need a lightweight way to block them off to prying eyes.

As Workers allow us to read request headers, we can block all traffic to a test site unless it has a specific header. Then all we have to do is install a Chrome Header add-on, insert our test string and allow this in the Worker JS.

This allows us to restrict access to test sites from the outside world without SSH’ing onto a server but also allow our developers access to them in a quick and simple way.

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

async function fetchAndApply(request) {  
  var ua = request.headers.get('user-agent');
    let url = new URL(request.url);

    if (ua.indexOf('MY-TEST-STRING')) {
        return fetch(request)
    } else {
        return new Response('Access Denied',
            { status: 403, statusText: 'Forbidden' })
    }
}

Conclusion

Cloudflare Workers give us the ability to analyze the requests before they reach the origin server. They are part of a wider industry shift towards serverless architecture and Edge Computing where computational code is located close the user instead of centrally stored on a web server.

Knowledge of the Workers and documentation is still sparse so it may be a while before these features are fully utilized but the power they give developers should not be understated and as understanding improves more use cases will be uncovered.

As Cloudflare powers 7 million websites we believe their products like Workers are going to have a large part to play in the evolution of the web. and will be investing our time in exploring them more.

What do you think of our Review Of Cloudflare Workers? Let us know in the comments below. We welcome all feedback both good and bad.

Posted in Reviews on Mar 25, 2018

Comments


Stefano 06.02.2018

Thanks for this amazing article, indeed it's the best article I found in the web, that describes what really CF workers do, and this is totally amazing! I've been also testing workers, and found really useful your simple scripts, it's really useful to be able to handle all these requests, before they reach the origin server. Cloudflare is really a game player over here, and starts the evolution of the web and at the same time saws, that JavaScript is the future! Thanks for writing for us such an amazing article, we are really can't wait to read your next project and review!

Leave a Comment: