Build a Link Shortener with Cloudflare Workers
Tags: serverless, tutorial, javascript, cloudflare
Published: 2021-07-23 21:10:13

[Cloudflare Workers](https://workers.cloudflare.com/) is a serverless platform that allows you to run back-end code in response to an event (like an HTTP request). Similar to other serverless platforms, this means that you won't have to keep a server running to wait for requests, allowing you to save money by only paying for resources you need.

Workers run on [Cloudflare's Edge Network](https://www.cloudflare.com/network/) and are incredibly fast, with a very generous free tier. In this 4-part tutorial series, we'll build one to power a link shortener that looks something like this:

![The final product: a URL shortener](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rw3p8x2va7ol42u9ofd.gif)

The finished product is also available on [GitHub](https://github.com/mm/cf-shortener) if you want to dive in and use the code for your own projects! For this project, we'll be using JavaScript, but Workers [support other languages too](https://developers.cloudflare.com/workers/platform/languages) (e.g Rust)

## What you'll need
- A [Cloudflare](https://cloudflare.com) account. The project we're building should fall within the Workers Free plan.
- Wrangler (the CLI for working with Workers) installed: e.g with NPM, `npm i @cloudflare/wrangler -g`: see [install instructions](https://github.com/cloudflare/wrangler)

## What we'll be building
Our link shortener has two main pieces that we'll build out:

1. A back-end that should be able to take a "long" URL, generate a "short" one, and return the shortened URL. It should also be able to return a redirect to the correct long URL, given a short URL.
2. A front-end to interact with the link-shortening back-end.

For (1), we can create a Worker to listen for HTTP requests and route accordingly:
- `POST /links`: Generate a new short URL from a long one, returning a short `slug` to access it at
- `GET /:slug`: Looks for a long URL with this `slug`, and redirects to it if it exists

In an application like this, the [Redis](https://redis.com) in-memory database may be an awesome choice, as we could store the slugs as keys and quickly access a long URL by slug. One huge benefit with Cloudflare Workers is that a [key-value store, Workers KV](https://www.cloudflare.com/products/workers-kv/) is built in and easily accessible from the Worker function. We'll be using Workers KV here.

For (2), our Worker can also serve static assets, and we'll store our HTML/CSS files using Workers KV too via [Workers Sites](https://developers.cloudflare.com/workers/platform/sites). For fun, the front-end will use Vue too. More on this soon!

## Getting started

1. Ensure you've installed [Wrangler](https://github.com/cloudflare/wrangler) as described above. Afterwards, run `wrangler login` and you'll be prompted to sign-in to your Cloudflare account.

2. Generate a new project using a JavaScript template, since that's what we'll be using for this tutorial:

    ```shell
    wrangler generate <project-name> 
    https://github.com/cloudflare/worker-template
    ```

3. This will create a new folder at `<project-name>`. Open up `wrangler.toml` in that folder, and set `account_id` to the account ID the Wrangler CLI returns. Also, set `type = webpack` instead of `javascript`, to package some dependencies we'll be installing.

Your Worker's code is in `index.js`:

```js
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})
/**
 * Respond with hello worker text
 * @param {Request} request
 */
async function handleRequest(request) {
  return new Response('Hello worker!', {
    headers: { 'content-type': 'text/plain' },
  })
}
```

What's happening here? When an HTTP request hits Cloudflare's edge network, and there's a Worker mapped to the route that got accessed, a `FetchEvent` object will get passed to the `fetch` event listener. The `FetchEvent` object has a `respondWith` method that lets us return a response right away. The Worker uses this to return a `Response` object with the `Hello worker!` text. For other things you can do with the `FetchEvent` object, check out the [FetchEvent lifecycle](https://developers.cloudflare.com/workers/learning/fetch-event-lifecycle) docs.

Run `wrangler dev` from your project directory. Behind the scenes, this [creates a tunnel](https://developers.cloudflare.com/workers/cli-wrangler/commands#dev) between your machine and the edge server that handles your requests. 

You should get a URL to try sending a request to:

```shell
💁  watching "./"
👂  Listening on http://127.0.0.1:8787
```
 
Make a request to that URL. You should see `Hello worker!` returned. If all is working so far, it's time to dive into building the back-end!

[➡️ Onward to building the back-end](https://dev.to/mmascioni/build-a-link-shortener-with-cloudflare-workers-the-back-end-35bd)