Creating a JavaScript Redirect Map in Cloudflare Workers, for free, unlimited redirects

Introduction to Cloudflare Workers: A Versatile Tool for Dynamic URL Redirection 


Cloudflare Workers is a cutting-edge platform that can be used to run a wide range of applications at the edge of the network. It offers an easy solution for website owners looking to improve the performance and security of their website, as well as developers who want to build custom applications. 

One of the most interesting features of Cloudflare Workers is the ability to create a dynamic redirect map. This allows website owners to redirect users visiting specific URLs to different destinations. With the help of Workers Routes, it's possible to redirect users who click on certain links to different pages on your site or even to entirely different websites. 

Implementing a Dynamic Redirect Map with Cloudflare Workers



This is an example of a Cloudflare Worker currently running on my website. Feel free to copy and paste it, depending on your needs. Obviously customise the redirect map so it doesn't link to my site and its resources (although feel free to go to https://ibaguette.com/api/x-url-test to see it in action!)

const redirectHttpCode = 301
const redirectMap = new Map([
  ['/api/x-url-test', 'discord:///invite/xz4SjyuBND'],
  ["/draggie-video-methodology", "https://www.ibaguette.com/2023/01/draggie-video-methodology.html"],
  ["/qr", "https://www.ibaguette.com/cheatsheets"],
["/2022/06/blog-post.html", "https://www.ibaguette.com/2022/06/AQA-Geography-GCSE-Paper2-CheatSheet.html"],
]
)

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

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

  const targetUrl = redirectMap.get(pathname)
  if (targetUrl) {
    return Response.redirect(targetUrl, redirectHttpCode)
  }

  return fetch(request)
}

The constant redirectMap holds a 2D array with the ending string of the URL and the URL to redirect to. This code even works with non-HTTPS protocols, as demonstrated by the example of redirecting a URL to a Discord invite link. 

In all code like this, there must be a FetchEvent listener when using Routes. Learn more about it at Cloudflare's docs here.

Setting Up the Redirect Map


To set up the redirect map, a trigger must be added in the Cloudflare Workers settings. To do this, go to the 'Triggers' section of your Worker, then click 'Add route'. The URLs you want the Worker to respond to can then be entered. Only routes of hostnames configured on Cloudflare can be specified.

It's important to note that the URL specified in the Worker route must overlap with the URL ending specified in the redirectMap, otherwise the redirect will not work. You can use the asterisk (*) character to create dynamic patterns that match multiple URLs. Learn more here.

To quickly access the URL of your Worker, you can use the following syntax: https://dash.cloudflare.com/<your site ID>/workers/services/view/<your worker name>/production/triggers 

Conclusion 


Cloudflare Workers is a powerful and flexible platform for redirecting URLs dynamically. Whether you're looking to improve the performance and security of your website or you're a developer looking to build custom applications, Workers is a valuable tool to have in your arsenal!

Comments