What is Cloudflare Workers?

Learn what is Cloudflare Workers, how it works, and how to get started with it and deploy your first serverless function on the edge of Cloudflare global network.

cloudflare

workers

By Pedro Rocha

Published Mar 11, 2024

Last Update Apr 10, 2024

Introduction

Cloudflare Workers is a platform built by Cloudflare that enables you to run serverless JavaScript and Python code on their Global Network - a network of hundreds data centers distributed around the world. This means that your code without having to manage infrastructure. You don’t need to worry about provisioning servers, scaling, or maintaining the infrastructure. You just write your code and deploy it to Cloudflare, and they take care of everything else.

You can use Workers to build entire application backends and also to supercharge existing websites with additional functionality. For example, you can use Workers to conduct A/B testing, personalize your user experience adding dynamic content that changes based on the user’s location and device, or to add security features, like rate limiting. You can also use Workers to improve the performance of your website by caching assets, or integrate it with third-party services, like databases, storage, or authentication providers.

Are you interested in learning more about Cloudflare Workers? In this article, we will cover:

  • How does Cloudflare Workers work?
  • What are the benefits of using Cloudflare Workers?
  • What is Cloudflare Workers used for?
  • How to get started with Cloudflare Workers?

How does Cloudflare Workers work?

Cloudflare Workers is a serverless platform, which is a type of cloud computing service that abstracts the infrastructure and allows you to run code without having to manage servers. The services is based on the concept of Function as a Service (FaaS), which is a category of cloud computing services that allows you to run individual functions or pieces of code in response to events, without having to manage the infrastructure. FaaS platforms are event-driven, which means that your code is only executed in response to an event, like an HTTP request, a database change, or a file upload, and this is what differes them from traditional server-based applications.

Cloudflare Workers is powered by V8, which is the JavaScript engine that powers Chromium and Node.js. So you can can write your serverless functions in JavaScript, and they will run on the edge of Cloudflare global network, closer to your users, improving the performance of your website.

Traditionally, serverless cloud providers package and run your application in containers that include the code, runtime, system tools, libraries, settings, and everything else it needs. They can be heavier and slow to start, and require lots of resources to run. They are usually managed by a container runtime, like Docker, and can be executed in any environment that supports containerization, like Kubernetes, AWS Fargate, or Google Cloud Run.

Different from other serverless platforms that run your application in containers, Cloudflare Workers use V8 isolates, which are a feature of the V8 engine that provides a way to run multiple instances of JavaScript code in separate, isolated contexts within a single process. This means that Cloudflare Workers can run your code in a more efficient way, with less overhead, and with a faster startup time, which is important for serverless functions that are executed in response to an event, like an HTTP request.

Originally, Cloudflare Workers supported only natively JavaScript, but you could also write code in languages that compile to WebAssembly, like Rust, C, C++, and Go. This was useful but required some extra work to compile the code to WebAssembly and to manage the bindings between the code and the Cloudflare APIs.

But now you can also write serverless functions natively and with first-class support in Python. Python support on Cloudflare Workers include the ability to use the majority of the Python standard libraries and built-in modules such as FastAPI, Langchain, and httpx. You can also access bindings to other products and services available at the Cloudflare Ecossystem, such as R2, KV, D1, Queues, Workers, AI, and more, and use secrets and environment variables to store sensitive information, like API keys and passwords.

What are the benefits of using Cloudflare Workers?

Easy to use

Cloudflare Workers is designed to be easy to use, with a simple and intuitive API that allows you to write and deploy serverless functions quickly and easily. You can write your code in JavaScript, TypeScript, or any other language that compiles to WebAssembly, and deploy it to Cloudflare with a single command.

Fast and efficient

Cloudflare workers is fast and efficient with a low startup time and low overhead, so they can respond to requests quickly and at scale. They run on the edge of Cloudflare global network, closer to your users, which means that they can improve the performance of your website by reducing latency and improving the time to first byte (TTFB). This is important for user experience and search engine optimization (SEO), as faster websites rank higher in search results and have higher conversion rates.

Secure

Cloudflare Workers run in a secure environment, with isolation between different workers, and they are protected by Cloudflare’s security features, like DDoS protection, WAF, and rate limiting. This means that you can run your serverless functions without having to worry about security, and focus on writing your code and deploying it to Cloudflare.

Generous free tier

Cloudflare is known to have a pretty generous free tier, so you can start using Cloudflare Workers without having to pay anything. This is great for small projects and personal websites that need to improve their performance without having to invest a lot of money. In the free tier, you can run up to 100,000 requests per day, which is enough for most small projects and personal websites. If you need more requests, you can upgrade to a paid plan, which is based on usage and starts at $5 per month.

What is Cloudflare Workers used for?

Cloudflare Workers can be used for a wide range use cases. Actually, the only limit is your own imagination. It basically runs code on the edge of Cloudflare global the network, so you can use it to perform all actions that you actually need or would want to perform in a traditional servers. Try it out and see what you can do with it at Cloudflare Workers Playground.

For you can feel inspired, bellow are some examples of what you can do with Cloudflare Workers. Remember that if you are looking for a fast and no code alternative for some of the examples below, you can use Flaremingo.

Flaremingo is a third-party platform built on top of Cloudflare Workers providing users with a user-friendly interface to create, manage, and deploy workers without the need for coding expertise. We provide a wide range of services that you can configure with a few clicks and deploy directly to your Cloudflare account. You can check it out all currently available services here.

Return a small HTML page or JSON response

Want to simply return a small HTML page or JSON response? You can use Cloudflare Workers to do that. Super useful for building simple APIs or serving static content.

If you want to spice it up what you can also do is to return dynamic content based on the user’s location. You can identify all the information you need by accessing the Cloudflare Object from within the worker script, and then return a response based on that information.


export default {
  async fetch(request) {
    let html_content = "";
    let html_style =
      "body{padding:6em; font-family: sans-serif;} h1{color:#f6821f;}";

    html_content += "<p> Colo: " + request.cf.colo + "</p>";
    html_content += "<p> Country: " + request.cf.country + "</p>";
    html_content += "<p> City: " + request.cf.city + "</p>";
    html_content += "<p> Continent: " + request.cf.continent + "</p>";
    html_content += "<p> Latitude: " + request.cf.latitude + "</p>";
    html_content += "<p> Longitude: " + request.cf.longitude + "</p>";
    html_content += "<p> PostalCode: " + request.cf.postalCode + "</p>";
    html_content += "<p> MetroCode: " + request.cf.metroCode + "</p>";
    html_content += "<p> Region: " + request.cf.region + "</p>";
    html_content += "<p> RegionCode: " + request.cf.regionCode + "</p>";
    html_content += "<p> Timezone: " + request.cf.timezone + "</p>";

    let html = `<!DOCTYPE html>
      <head>
        <title> Geolocation: Hello World </title>
        <style> ${html_style} </style>
      </head>
      <body>
        <h1>Geolocation: Hello World!</h1>
        <p>You now have access to geolocation data about where your user is visiting from.</p>
        ${html_content}
      </body>`;

    return new Response(html, {
      headers: {
        "content-type": "text/html;charset=UTF-8",
      },
    });
  },
};


Return a conditional response based on the incoming request properties

You can also use Cloudflare Workers to return a conditional response based on the incoming request properties, like the user agent, IP address, or hostname. This is useful for blocking requests from malicious bots, or for serving different content based on the user’s location or device. You can use the request object to access the incoming request properties, and return a response based on those properties.


export default {
    async fetch(request) {

        const userAgent = request.headers.get("User-Agent");
        if (userAgent === "MaliciousBot") {
        return new Response("Sorry, this page is not available for MaliciousBot", {
            status: 403,
        });
        }

        const clientIP = request.headers.get("CF-Connecting-IP");
        if (clientIP === "1.2.3.4") {
            return new Response("Block the IP 1.2.3.4", { status: 403 });
            }
        return fetch(request);;
    },
};


Modify the incoming request or outgoing response

You can use Cloudflare Workers to modify the incoming request or outgoing response, like adding or removing headers, or changing the status code. Doing that can be useful for adding security headers, like Content Security Policy (CSP) or Strict-Transport-Security (HSTS), or for redirecting requests to a different URL. You can use the request object to access the incoming request properties, and the response object to modify the outgoing response.


export default {
    async fetch(request) {
        const response = await fetch(request);
        response.headers.set("X-Frame-Options", "DENY");
        response.headers.set("X-Content-Type-Options", "nosniff");
        response.headers.set("X-XSS-Protection", "1; mode=block");
        return response;
    },
};


You can use Cloudflare Workers to add hotlink protection to your images, which means that you can prevent other websites from embedding your images in their pages. This is useful for preventing bandwidth theft, and for ensuring that your images are only displayed on your website. You can use the request object to access the incoming request properties, and return a response based on those properties.


export default {
  async fetch(request) {
    const HOMEPAGE_URL = "https://tutorial.cloudflareworkers.com/";
    const PROTECTED_TYPE = "image/";

    const response = await fetch(request);

    const referer = request.headers.get("Referer");
    const contentType = response.headers.get("Content-Type") || "";

    if (referer && contentType.startsWith(PROTECTED_TYPE)) {

      if (new URL(referer).hostname !== new URL(request.url).hostname) {

        return Response.redirect(HOMEPAGE_URL, 302);
      }
    }

 
    return response;
  },
};
// Source: Cloudflare Docs



How to get started with Cloudflare Workers?

1. Create a Cloudflare account

To get started with Cloudflare Workers, you need to have a Cloudflare account, and have npm and Node.js installed on your computer. If you don’t have a Cloudflare account, you can sign up for free at Cloudflare. If you don’t have npm and Node.js installed on your computer, you can download and install them from Node.js.

2. Scaffold a new Cloudflare Workers project

Once you have a Cloudflare account, and npm and Node.js installed on your computer, you can start a new Cloudflare Workers project by running npm create cloudflare@latest in your terminal: By following the wizard you will create a scaffolding with evrything you need to start developing your Cloudflare Worker. Basically, you’ll have a project directory with a wrangler.toml file, a package.json and package-lock.jon files, a node_modules directory, and a src directory with a index.js file.

  • The wrangler.toml is a configuration file that contains the settings for your Cloudflare Workers project. You can access all the settings and configurations that you can use in the Cloudflare Workers documentation.

  • The package.json file contains the metadata for your Cloudflare Workers project, including the name, version, description, and dependencies. You can use npm to install additional dependencies, like third-party libraries or frameworks, and manage your project’s dependencies.

  • The package-lock.json file contains the exact version of each dependency that is installed in your Cloudflare Workers project, including the transitive dependencies that are required by those dependencies.

  • The node_modules directory contains the dependencies for your Cloudflare Workers project, including the third-party libraries or frameworks that you have installed with npm.

  • The src directory contains the source code for your Cloudflare Workers project, including the index.js file, which is the entry point for your serverless functions.

3. Develop and deploy your Cloudflare Workers

Now that you’ve installed the Cloudflare workers project, you can start using the Wrangler CLI for developing, testing, and deploying your Cloudflare Workers.

For development, you can run npx wrangler dev to start a local development server that will run the worker on your computer. This is useful for testing your functions before deploying them to Cloudflare.

If you selected the "Hello World" script as the type of application you want to create during the scaffolding, you can access the local development server at http://localhost:8787/ and see Hello World! printed on the screen.

You can modify the code in the index.js file, and the changes will be automatically reflected in the local development server. Once you are happy with your changes, you can deploy to Cloudflare by running npx wrangler deploy. You’ll be prompted to login to your account, and then your your code will be deployed to the Cloudflare Global Edge Network. You’ll be able to access it live on the internet at the URL provided by the Wrangler CLI.

Conclusion

That’s it, you now know what are Cloudflare Workers and how to get started with them. If you wish, you can also use Flaremingo to create, manage, and deploy workers for you. We provide a wide range of services that you can configure with a few clicks and deploy directly to your Cloudflare account. You can check it out all currently available services here.

A Flaremingo service costs $14.99, with an exclusive 60% discount available during the Beta phase. It’s a lifetime access offer, meaning once you purchase you can created and deploy as many workers as you want.

Want to supercharge your website with serverless functions designed for optimizing SEO, performance, security, marketing, and more? Try Flaremingo:

Create a free account!

Want to supercharge your website with serverless functions designed for optimizing SEO, performance, security, marketing, and more? Try Flaremingo:

Create a free account!