Redirection done better, with CloudFlare Workers

Mohammed Brückner
3 min readJul 3, 2021

Creating a redirect is in itself not hard. A redirect based on a mix of certain conditions, now that can get tedious. Often, you end up dealing with running apps for nothing but redirecting. Does it have to be that way?

No, with CloudFlare Workers you have an easy to use and quite powerful tool at hands to do the job — without any infra management at all. And you get 100k free API calls per day. Not to shabby and that’s why I want to show you how to do use CloudFlare Workers for your redirection needs.

A simple HTTP endpoint using CloudFlare Workers

Creating a simple HTTP endpoint is super simple and fast to do, e.g. with a JS like this:

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
var today = new Date();
var dayofthemonth = today.getDate(); //retrieves a numeric value
var month = today.getMonth();
var debug = '';
if (dayofthemonth == 17 && today.getMonth() == 11) {
debug='It is 17th of December';
} else {
debug='It is not 17th of December';
}
return new Response('Important message: ' + debug, {status: 200})
}

Date-based re-directs

Now let us imagine you want to have a URL redirect that does some validation, eg some basic date checking.

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
var today = new Date();
var dayofthemonth = today.getDate(); //retrieves a numeric value
var month = today.getMonth();
var debug = '';
var before='http://bit.do/ai4ia';
var after='https://github.com/MoBRUEC';
if (dayofthemonth !=22 && today.getMonth() != 5) {
return Response.redirect(before, 302);
} else {
return Response.redirect(after, 302);
}
}

And the CloudFlare “Quick Edit” UI even features some primitive intellisense.

The catch here being that a default timezone is used.

Here’s how you’d deal with different timezones:

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url1 = "https://google.com"
const url2 = "https://bing.com"
// If no timezone is needed, just use a plain UTC date
// const date = new Date()
// If a timezone is needed, use toLocaleString and pass a timeZone option
const date = new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
// Coerce the date string with correct timezone back into a date
const hour = new Date(date).getHours()
const url = hour < 12 ? url1 : url2
const response = await fetch(url)
return response
}

You could do way more than that with these Workers:

https://developers.cloudflare.com/workers/examples/modify-response

In fact, there are plenty more examples of what you could do:

https://developers.cloudflare.com/workers/tutorials

Bypassing the Cache

CloudFlare workers aggressively cache everything.

This is important for example for the cases when you fetch data from external URIs within your cloud worker. Some tips here:

https://community.cloudflare.com/t/bypassing-cloudflare-cache/82387/6

Beware, though! The Cloud Workers limits in the unpaid version of CloudFlare Workers do not suggest you should fetch data from external resources but rather stick to very simple use cases like redirection, changing response headers and such.

--

--

Mohammed Brückner

Author of "IT is not magic, it's architecture", "The DALL-E Cookbook For Great AI Art: For Artists. For Enthusiasts."- Visit https://platformeconomies.com