Creating and deploying a Cloudflare Worker
In the previous post, I showed how to create and deploy a Lambda function to the AWS using the Cloud development Kit (CDK). Today I want to do the same but with a different cloud provider and a different tooling.
What is Cloudflare and Cloudflare Workers?
Cloudflare is a company that started as a content delivery network provider back in 2009. Content delivery network (CDN) is a geographically distributed network of proxy servers that cache content of a website to speed up the loading times.
For example, your website is hosted in Europe, which means that visitors from Europe load it quickly, but it takes longer to load it to visitors from Australia.
A content delivery network solves this problem by caching your website at a proxy server located in many locations scattered around the globe. When a visitor requests a page from your website, it serves the page from the nearest proxy server, thus reducing the load time.
In 2017, Cloudflare launched a new service called Cloudflare Workers. Cloudflare Workers is a hosting platform for serverless functions similar to AWS Lambda. The main difference is in pricing, supported programming languages, and the fact that Cloudflare Workers are invoked from the closest server to the visitor rather than from a specific region like it is with AWS Lambda. I should mention, though, that AWS also has a service Lambda@Edge that offers similar functionality as Cloudflare Workers.
Prepare the development environment
You can create a worker function using the Cloudflare dashboard, but for some people, including me, it’s more convenient to use the command line interface.
There is a tool called Wrangler that can be used to set up and manage Cloudflare infrastructure using CLI.
Wrangler CLI requires having Node.js and npm installed. If you don’t have it already, head over to https://nodejs.org/en/download to get it.
Install the Wrangler using the following command:
$ npm install -g wrangler
Create a new Worker project
A Worker project is a folder containing the source of a worker function, files necessary to build the function, and a Wrangler configuration file.
Run the command below to start the new project creation wizard.
$ wranger init
The setup wizard will ask you a few questions about the new project. When asked about the project type, select the “Hello World” Worker project.
What the Worker function looks like
The source file on the Worker function will be either src/index.js
or src/index.ts
,
depending on which answer you chose when the wizard asked you whether to use TypeScript or not.
Below is the TypeScript version of Hello World worker code.
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello World');
},
};
The function is supplied with a request parameter, which we can use to determine the HTTP method of the request, read the request body, form data, and headers.
It is followed by a second parameter, env
,
which is used to pass the environment variables from the Wrangler configuration file or the Cloudflare dashboard.
The execution context parameter is intended for controlling the worker runtime. You can use it to ask the runtime to keep the worker running after the response was sent, or configure what to do when an unhandled exception occurs during the execution of the worker function.
Test the Worker function locally
The Cloudflare Wrangler offers a local testing environment. It was something that I miss when I work with the AWS CDK. However, it would be unfair not to mention that you can achieve that with the AWS CDK, but it requires an additional tooling to install and set up.
I like the fact that with Cloudflare it works right out of the box. All you have to do is to run the following command:
$ wrangler dev
The command spins up a local development server reachable at http://localhost:8787 that you can use to test the function.
Deploy the Worker function to Cloudflare
To deploy the project to the cloud, simple run the command below. After a short moment, a URL where your function was deployed should appear on the screen.
$ wranger deploy
...
Uploaded helloworld (2.04 sec)
Published helloworld (1.43 sec)
https://helloworld.aquarius.workers.dev
Let’s test the function to see if it works:
$ curl https://helloworld.aquarius.workers.dev
Hello World!
Multiple deployments
Wrangler supports deploying multiple versions of your Worker function, which allows you to create separate runtime environments for different purposes. For example, having separate environments for production and test is a good practice because it allows you to test your code in isolation from the actual users.
For example, to create a new environment called dev
,
open the wrangler.toml
and add an empty section [env.dev]
.
All variables for this specific environment should be included in this section.
name = "helloworld"
main = "src/index.ts"
compatibility_date = "2023-10-30"
vars = { ENVIRONMENT = "prod" }
[env.dev]
vars = { ENVIRONMENT = "dev" }
To deploy a specific environment, use the -e
or --env
option when deploying the Worker function.
In this particular case, to deploy the dev
environment, the deployment command should look like this:
$ wrangler deploy -e dev
Delete the function from Cloudflare
When you don’t need the worker function anymore, you can delete it using the following command:
$ wrangler delete
Conclusion
In this article, we learned how to deploy a serverless function to Cloudflare.
Using Cloudflare Wrangler to deploy a serverless function was much easier than doing the same this with the AWS CDK, which I wrote about in my previous article.
If you’re interested in learning more about the differences between those two services, I recommend reading this article.