X
Popular Searches

How to Use CloudFlare Workers to Run JavaScript On The Edge

CloudFlare

The closer to the edge that you can run code or return data to a visitor, the faster the user experience will be. With that in mind, CloudFlare released a product named CloudFlare Workers, which allows running JavaScript code on edge servers. This allows you to intercept a request, act upon that request, and return the result all on the edge, with the potential to never touch your origin server.

This opens up a world of possibilities, not only in regards to performance, but unique applications running nearly entirely on the edge. Taking advantage of CloudFlare’s massive infrastructure, capacity, and edge locations means that this type of product is one of a kind.

Of course, with any new solution like this, it might be difficult to come up with potential applications. Though there are many, what are some practical uses? In this article, we explore one potential use case, that of performing redirects directly on the edge.

Configuring the CloudFlare Worker

Assuming that you already have a domain that is proxied through CloudFlare, we can enable workers and start testing our code, even before we deploy in production. Once you log in to the CloudFlare Dashboard, you will notice an icon for Workers. What’s very convenient about this environment is that CloudFlare gives you a development environment to test out everything before you deploy your worker to your live site.

Create a worker.

Click on “Create a Worker” to generate a development environment pointed to a randomly generated worker sub-domain to allow for testing.

Generated development environment pointed to a randomly generated worker sub-domain.

Let’s take a look at the development environment to understand how this can help us. There are three main sections. On the left side, we have a code editor and on the right, we have two views. One is the HTTP view where we can construct specific requests to our Worker and see the response, and the second is the Preview tab where we can see what the page itself would look like.

Now that we have a code environment set up, let’s create a simple redirect that we can expand upon later.

Developing the Redirect Code

There is a boilerplate code that will serve as a great start to our redirect code. In the first section, the addEventListener is what first intercepts the incoming request. That request is then sent to the handleRequest function for processing.

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

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
 // Redirect logic to go here 
}

The core idea is that we will read the pathname of the incoming request URL and decide where to redirect. By using the URL type, we can easily map our incoming pathname to a location. In this example below, we are using a switch statement to set the location based on the path and return a 301 permanent redirect.

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

async function handleRequest(request) {
  let requestURL = new URL(request.url)
  let path       = requestURL.pathname.split('/redirect')[1]

	switch (path) {
		'/test1' {
			let location = 'https://mysite.com/newlocation1'
			break
		}
		'/test2' {
			let location = 'https://mysite.com/newlocation2'
			break
		}
	}

  if (location) {
    return Response.redirect(location, 301)
  }
  
  return fetch(request)
}

Enhancing the Redirect Script

This works well, but there is a more efficient and easier to manage the way of mapping the redirects. By using the JavaScript Map construct, we can create an easy to reference list of redirects. Let’s move our redirects into a Map construct and refactor our code to make it work a bit better.

const redirectMap = new Map([
  ['/test1', 'https://mysite.com/newlocation1'],
  ['/test2', 'https://mysite.com/newlocation2'],
  ['/test3', 'https://mysite.com/newlocation3'],
  ['/test4', 'https://mysite.com/newlocation4'],
])

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

async function handleRequest(request) {
  let requestURL = new URL(request.url)
  let path       = requestURL.pathname.split('/redirect')[1]
	let location   = redirectMap.get(path)

  if (location) {
    return Response.redirect(location, 301)
  }
  
  return fetch(request)
}

Deploying

Now that our script is functional, we need to map this to a domain. After clicking on Save and Deploy we need to navigate back to our dashboard and find the domain that we are mapping this script too.

Select the domain we want to apply this worker to, then navigate to the “Workers” tab. Select the “Add Route” button, and you are able to define the script and route. What this also means is that you can create multiple scripts and routes that they apply to.

Select domain to apply worker to, then navigate to "Workers" tab. Select "Add Route" button, define script and route.

Under the “Route” entry, we need to define where the link will go. Most likely we would set up a route such as:

*.mysite.com/*

The above route matches all URLs and schemes for the site. Because we are looking for the ending path, we will look at every request coming through and test for that. Finally, we will select the Worker that we have created to deploy to this zone.

Add route.

Something to keep in mind is that assigning a CloudFlare Worker to a script and route will make that worker instantly take effect. This also means that changes, errors and all, take effect instantly as well.

Future Possibilities

CloudFlare has made several other tools and capabilities available using or integrating CloudFlare Workers. There is a key-value store that allows for eventually consistent data storage, accessible by any CloudFlare Worker on any edge server.

Using Wrangler, a command line tool, you can even provision an entire static site with the files stored within the KV Store and served using CloudFlare Workers scripts. There are many possibilities that this raises and what can be created using CloudFlare Workers.

Conclusion

CloudFlare Workers is a very powerful tool that allows for the unique ability to quickly act upon edge requests. By using this to move our normal application logic to the edge, not only do we decrease response time, but we also avoid taxing our origin servers as well.

Adam Bertram Adam Bertram
Adam Bertram is a 20+ year veteran of IT and an experienced online business professional. He’s a consultant, Microsoft MVP, blogger, trainer, published author and content marketer for multiple technology companies. Catch up on Adam’s articles at adamtheautomator.com, connect on LinkedIn, or follow him on Twitter at @adbertram. Read Full Bio »

The above article may contain affiliate links, which help support CloudSavvy IT.