Tutorial

Serverless Cloudflare Workers Are Pretty Awesome

Draft updated on Invalid Date
    Default avatar

    By Ahmad Awais

    Serverless Cloudflare Workers Are Pretty Awesome

    This tutorial is out of date and no longer maintained.

    Introduction

    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.

    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
    • You can change the behavior of existing apps
    • And do all that without configuring or maintaining infrastructure

    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 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.

    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 Cloudflare 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?!'));
    })
    

    #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);
    }
    

    #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 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.`);
        }
    }
    

    Conclusion

    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.

    Learn more about us


    About the authors
    Default avatar
    Ahmad Awais

    author

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    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!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel