Build a Link Shortener with Cloudflare Workers

mmascioni

Matt Mascioni

Posted on July 23, 2021

Build a Link Shortener with Cloudflare Workers

Cloudflare Workers 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 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

The finished product is also available on GitHub 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 (e.g Rust)

What you'll need

  • A Cloudflare 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

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 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 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. For fun, the front-end will use Vue too. More on this soon!

Getting started

  1. Ensure you've installed 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:

    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:

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' },
  })
}
Enter fullscreen mode Exit fullscreen mode

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

Run wrangler dev from your project directory. Behind the scenes, this creates a tunnel between your machine and the edge server that handles your requests.

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

šŸ’  watching "./"
šŸ‘‚  Listening on http://127.0.0.1:8787
Enter fullscreen mode Exit fullscreen mode

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

šŸ’– šŸ’Ŗ šŸ™… šŸš©
mmascioni
Matt Mascioni

Posted on July 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related