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
- Get a Cloudflare account and enable Workers
- Install
wrangler, Cloudflare's CLI tool for working with Workers, and set it up using your Cloudflare API token - Copy the Workers JavaScript template repository
- 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}); } - Create your own
urls.jsonfor mapping paths( e.g.fooforhttps://your-domain.com/foo) to redirect URLs. - Set
typetowebpackinwrangler.toml(see the docs) - Set your Account ID in
wrangler.tomlthen runwrangler publishto deploy your app to a default subdomain ofworkers.dev - To get it on your custom domain, set
workers_devtofalse, andzone_idinwrangler.tomlto the Zone ID of your domain in Cloudflare, androutetoyour-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