Serverless CloudFlare Workers Are Pretty Awesome
Publikováno: 21.2.2019
Serverless is the new black. I mean 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 aud...
Serverless is the new black. I mean 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 (check out that coolest new domain extension .dev
Google just made available).
Today, let's explore what the heck is this new serverless platform about, how is it different than other serverless platforms (did someone say no cold starts!), and what do you say, let's write our first CloudFlare Worker.
What Are CloudFlare Workers?
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
- You get a serverless execution environment
- You can create entire new serverless apps
- What?! You can change the behavior of existing apps
- and do all that without configuring or maintaining infrastructure
????all this sounds pretty awesome, tell me more! — Happy to oblige.
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
- 165 Data Centers: CloudFlare is known for having one of the biggest CDN networks in the world. Just to put things in perspective here, Cloudflare’s network capacity is 15x bigger than the largest DDoS attack ever recorded. It has a 25 Tbps of capacity, it can handle any modern distributed attack.
- Dirt Cheap: The entire network of data centers can be used for your serverless apps. Which is amazing for scaling your next awesome API side project. It's dirt cheap. $5 per month for 10 million requests and then $0.5 per million requests. Folks like Troy Hunt are using Cloudflare Workers to identify pwned passwords.
- Standard Service Workers API: The power of Cloudflare Workers comes from the ability to run standard JavaScript written against the Service Workers API on Cloudflare's edge nodes around the world.
????yup, that's how I felt at first; tell me moaar!
Potential of 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 CoudFlare are:
- Load balance between multiple origins to improve speed or reliability.
- Render HTML templates while fetching dynamic content from your origin.
- Dynamically respond to requests without connecting to an origin server.
- Generate parallel requests to different services and combine the responses.
- Create custom security rules and filters to block unwanted visitors and bots.
- Perform data sanitization & validation before sending a request to origin.
- Decide which requests are cacheable to improve cache hit rate.
- Deploy fast fixes in secs without having to update your origin server.
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.
CloudFlare Workers Examples
Let's create a couple of simple CloudFlare Workers to see what we can accomplish. Test out Workers free of charge on cloudflareworkers.com.
1 Hello World Example
addEventListener('fetch', event => {
event.respondWith(new Response('Hello World; Learning CloudFlare Workers, eh?!'));
})
Test this example here →
2 Block Access to Specific Countries
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);
}
Test this example here →
3 Give Purchasing Power Parity (PPP) Discounts
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 another debate, 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 ofcoruse 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.`);
}
}
Test this example here →
Your Turn
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 (tip: 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. Reach out (and say Hi) on Twitter if you'd like to chat about this. Peace! ✌️