Skip to content

World's Simplest URL Shortener using Cloudflare Workers

A URL Shortener is a very common proof-of-concept app to build when learning web development, and this one is nothing new. I wanted to try out Cloudflare's Workers, a super-simple Serverless platform built on their Edge Network.

If you're familiar with JavaScript Service Workers, you'll be able to write a Worker.

Here's step-by-step instructions for setting it up, also available on GitHub

  1. Get a Cloudflare account and enable Workers
  2. Install wrangler, Cloudflare's CLI tool for working with Workers, and set it up using your Cloudflare API token
  3. Copy the Workers JavaScript template repository
  4. Write your code in index.js - here's mine:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    // Copyright Patrick Reader 2020, Licensed under the MIT Licence https://github.com/pxeger/url-shortener/blob/master/LICENCE.txt
    const urls = require('./urls.json');
    
    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request));
    })
    
    async function handleRequest(request) {
      const path = new URL(request.url).pathname.substring(1);
      console.log(request.headers['user-agent'], new Date(), path);
      if (path in urls) return new Response(null, {status: 308, headers: {location: urls[path]}});
      else return new Response('404 not found?', {status: 404});
    }   
    
  5. Create your own urls.json for mapping paths( e.g. foo for https://your-domain.com/foo) to redirect URLs.
  6. Set type to webpack in wrangler.toml (see the docs)
  7. Set your Account ID in wrangler.toml then run wrangler publish to deploy your app to a default subdomain of workers.dev
  8. To get it on your custom domain, set workers_dev to false, and zone_id in wrangler.toml to the Zone ID of your domain in Cloudflare, and route to your-domain.com/*.

This URL shortener can only have new URLs added by modifying urls.json and re-deploying. That may not be what you want, but it's perfect for me because I want mine to be private. You could look in to Cloudflare Workers KV to create a dynamic system, but for me the $5/month price floor was a little too steep for something this mundane.

Mine's deployed at pxeger.net.


First published: 2020-08-06
Last updated: 2020-08-09