Building Your First Application with Cloudflare Workers

Cloudflare Workers is a serverless platform. It allows you to run your application logic on Cloudflare's global edge network. Which means, it is closer to users for low-latency and high-performance execution.

Unlike others serverless platforms (e.g., AWS Lambda), Workers have virtually no cold start latency. This ensures faster response times, even for the first request. So they are perfect for use cases where speed and scalability are crucial.

Yet, you can use Workers for a large range of tasks. Creating APIs, handling authentication, routing request, and caching are a few examples. And this is thanks to its simple integration with Cloudflare services.

What are we building?

This post will explore how to build and deploy your first Cloudflare Worker. You will create an API to shorten URLs that will

  1. Have a POST /shorten endpoint that will receive the url and will generate a shorter url with a unique hash

  2. Store the mapping of the short URL to the original URL using Cloudflare KV (Key-Value Storage).

  3. Have a GET /:slug endpoint that will redirect users to the original URL

Prerequisites

Before continue, make sure you complete the following steps

  1. Sign up for a Cloudflare account ↗ if you have not already.

  2. Install npm ↗.

  3. Install Node.js ↗.

Project setup

Finally let's start building our API. The first thing we need to do is to scaffold the project. For this we will use the official create-cloudflare-cli (aka C3). C3 is a command-line tool designed to help you set up and deploy new applications to Cloudflare.

To use it we will need to open a new terminal and run the following

npm create cloudflare

This command will show some setup questions. In order to create a project with only the essential, you need to select the following options:

  • For What would you like to start with?, choose Hello World example.

  • For Which template would you like to use?, choose Hello World Worker.

  • For Which language do you want to use?, choose Typescript.

  • For Do you want to use git for version control?, choose Yes.

  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

The above command will create some configuration files for Typescript and Vitest. The most critical files here will be src/index.ts and wrangler.toml.

src/index.ts is the root of our workers. Here's where we will receive all the traffic. The wrangler.toml file is the configuration file used by Wrangler, Cloudflare's command-line tool for managing and deploying Cloudflare Workers. This file defines the settings and metadata for your Worker project, including the environment settings, KV namespaces, account details, and other Worker-specific options.

The /shorten Endpoint

To handle the incoming request we would need to modify the fetch method exported on src/index.ts, and add the following.

if (request.method === 'POST' && request.url.endsWith('/shorten')) {
	const body = (await request.json()) as { url: string };
	const originalUrl = body.url;

	if (!originalUrl) return new Response('url field is required');

	// Generate a random short code
	const slug = Math.random().toString(36).substring(2, 8);

	return new Response(
		JSON.stringify({
			slug,
			originalUrl,
			shortUrl: `/${slug}`,
		}),
		{ headers: { 'Content-Type': 'application/json' } }
	);
}

With this, we use the incoming request to execute our code only when the method is POST, and the URL is /shorten. Then, we extract the original URL from the request body and create a new random string. Finally, we return a JSON with the original URL and the new slug.

If we start the development server with npm run dev we should be able to do something like this:

curl -X POST -H 'Content-Type: application/json' -d '{"url":"https://example.com/testing"}' http://localhost:8787/shorten

Creating a KV Namespace

Workers KV is a globally distributed key-value storage system designed for fast access from Cloudflare's edge network. It is perfect for storing our generated slug so we can retrieve the original URL later.

First of all, we will need to authorize Wrangler with our Cloudflare account.

npx wrangler login

After completing the OAuth flow, we can create a new KV namespace with the following command.

npx wrangler kv namespace create URL_STORE

This will output some lines we need to add to our wrangler.tool. Then, if you are using Typescript, we can run npm run cf-typegen to generate the types for our new KV Namespace.

Now, we can access URL_STORE within the env parameter. Adding the following line will save the original URL so we can access it later.

env.URL_STORE.put(slug, originalUrl);

/{slug} Endpoint

Now we need to create the endpoint to redirect to the original url. For this we will add the following to the fetch function.

if (request.method === 'GET') {
	const url = new URL(request.url);
	const path = url.pathname.substring(1); // Extract the short code

	if (path) {
		// Lookup the original URL in the KV store
		const originalUrl = await env.URL_STORE.get(path);

		if (originalUrl) {
			// Redirect to the original URL
			return Response.redirect(originalUrl, 301);
		}
	}
}

To test this we should be able to open our browser and go to localhost:8787/{slug}. The browser will redirect us to the saved url.

Deploying to Cloudflare

Deploying our code to Cloudflare is as simple as using npm run deploy in console. This will deploy our worker to https://url-shortener.{your_username}.workers.dev.

Next steps

Although the application we created on this tutorial is simple, we can added more complex features with low effort.

A few features we can add to this application could be:

  1. Using a lightweight web framework like Hono to use middlewares and a more robust router matcher.

  2. Improve Wrangler configuration to have different environments to run and test our application.

  3. Setup CI/CD pipeline to test and deploy our application with GitHub Actions

Conclusions

Cloudflare Workers is a powerful but still easy-to-use tool for creating high-performance applications. Its simplicity allows us to create an up-and-running application with just a few steps. However, we could also scale and add robustness as needed.

Feel free to refers to the official documentation to learn more about Cloudflare workers