By Ahmad Awais
This tutorial is out of date and no longer maintained.
Everybody I know is moving to the serverless platforms or launching one. OK, maybe not everyone but Cloudflare is definitely moving in this direction with an audacious relatively new project called Workers.dev.
Today, let’s explore what this new serverless platform is about, how is it different than other serverless platforms, and write our first Cloudflare Worker.
Let’s understand Cloudflare Workers deeply. What’s the big catch here?
Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure. — Cloudflare Docs
Serverless Computing with Cloudflare Workers. The Network is the Computer. Build serverless applications on Cloudflare’s global cloud network of 165 data centers. — Cloudflare Workers
So, the Cloudflare Workers let you run JavaScript in hundreds of data centers around the world. Using a Worker, you can modify your site’s HTTP requests and responses, make parallel requests, or generate responses from the edge.
Some more examples shared by Cloudflare are:
All of these actions happen inside Cloudflare’s network. Yes, your code will be deployed to hundreds of data centers around the world returning responses to your users faster than your origin ever could. You get all the speed and security of Cloudflare CDN with all the power of JavaScript.
Let’s create a couple of simple Cloudflare Workers to see what we can accomplish. Test out Workers free of charge on cloudflareworkers.com.
addEventListener('fetch', event => {
event.respondWith(new Response('Hello World; Learning Cloudflare Workers, eh?!'));
})
You can enable IP Geolocation to have Cloudflare geolocate visitors to your website and pass the country code to you in ISO 3166-1 Alpha 2
format. That sends the country code to a Cloudflare Worker in the form of a header called cf-ipcountry
— we can play around with it to block access on a specific service or API to a country.
/**
* Cloudflare Worker.
*
* Block access to given countries.
*/
addEventListener('fetch', event => {
event.respondWith(block(event.request));
});
// Add countries to this Set to block them.
const countries = new Set([
'US', // United States.
'SG', // Singapore.
'BR', // Brazil.
'PK', // Pakistan.
'NG' // Nigeria.
]);
/**
* Block requests.
*
* @param {*} request User's request.
*/
async function block(request) {
// Get country value from request headers.
const country = request.headers.get('cf-ipcountry');
// Find out if country is on the block list.
const isCountryBlocked = countries.has(country);
// If it's on the blocked list, give back a 403.
if (isCountryBlocked) {
return new Response(`SORRY: This page not available in your country!`, {
status: 403,
statusText: 'Forbidden'
});
}
// Catch-all return of the original response.
return await fetch(request);
}
I teach a course on VSCode Power User where I offer Purchasing Power Parity (PPP) discounts to developers from countries where the economy is not as strong as the US and many others. There’s up to 60% discount available. While building PPP is a whole other topic, you can very easily see how Cloudflare Workers can help here.
Down here, I have built a simple model that checks user’s country to respond back with a discount percentage — which, of course, can be used to configure a DOM element or another API as a whole.
/**
* Cloudflare Worker.
*
* Purchasing Power Parity Discounts.
*/
addEventListener('fetch', event => {
event.respondWith(pppDiscount(event.request));
});
// Country with percentage of discount.
const discount = {
UK: 10,
CA: 20,
PK: 60,
NG: 60,
IN: 60,
BR: 60
};
/**
* Give Purchasing Power Parity Discounts.
*
* @param {*} request User's request.
*/
async function pppDiscount(request) {
// Get country value from request headers.
const country = request.headers.get('cf-ipcountry');
const yourDiscount = discount[country];
// If no discount.
if (yourDiscount === undefined) {
return new Response(`No Purchasing Power Parity Discount in your country.`);
} else {
// Return discount.
return new Response(`Purchasing Power Parity Discount in ${country}: ${yourDiscount} percent.`);
}
}
Go ahead and try out Cloudflare Workers. I for one am a big fan of workers and have just booked myself a subdomain via Workers.dev.
Note: Try double-clicking anywhere on the page and see what happens.
You should also check out the documentation as well as the Cloudflare Worker Recipes.
I hope you enjoyed the piece.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.