Free URL shortener with Cloudflare Workers

After reading that URL shorteners set ad tracking cookies today, I decided to share how to get a decent shortener set up in a few minutes for free on Cloudflare Workers. It has a free tier of 100k requests per day, which is more than enough for most use cases.

To set it up, you will need a domain, but if you need an URL shortener you probably have some domain already. We used go.surferseo.com subdomain which can make a good default.

The code to get it working is just a few lines of JavaScript:

const redirects = new Map([
["cloudflare-shortener", "https://lucjan.medium.com/free-url-shortener-with-cloudflare-workers-125eaf87b1ec"],
["neil-pattel-copied-my-design", "https://lucjan.medium.com/how-neil-patel-copied-my-design-and-im-not-even-mad-ede6e99648c0"],
])
addEventListener('fetch', event => {
event.respondWith(handleRedirect(event.request));
})
async function handleRedirect(request) {
let pathname = new URL(request.url).pathname.replace("/", "");
let location = redirects.get(pathname);
return location
? Response.redirect(location, 301)
: new Response("Not Found", {status: 404})
}

In this case, whenever I go to go.surferseo.com/cloudflare-shortener, I’d be redirected to this very article. Handling another path is just a matter of adding one line of JS (which could be further simplified into Cloudflare KV store to make non-technical people lives easier).

How to get it working

Once you add your domain to Cloudflare, go to Workers tab:

Image for post
Image for post

then Manage Workers:

Image for post
Image for post

Create a Worker:

Image for post
Image for post

Replace the JS code with the one above and hit Save and Deploy, then confirm:

Image for post
Image for post

Your shortener will be available under *.workers.dev domain and you can test if everything works fine.

If it does, go back to the Workers tab in your domain settings and hit Add route just under Manage Workers, typing the subdomain (or naked domain) and selecting the worker you just created.

Image for post
Image for post

The last step is to add dummy, proxied (orange cloud) subdomain in the DNS tab, so the worker can pick it up:

Image for post
Image for post

If I managed to explain the steps well and you could follow through, you should have your very own, simple and free URL Shortener working!

To add, remove or change routes, just head back to Manage Workers, click the worker you created and then Quick Edit:

Image for post
Image for post

After changing the routes and hitting Save and Deploy (don’t forget about comma after each one), it will be available in a few seconds.

Have fun!

Written by

Co-founder and CTO at Surfer. Loves building web products.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store