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"],
["surfer", "https://surferseo.com"],
])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:
then Manage Workers:
Create a Worker:
Replace the JS code with the one above and hit Save and Deploy, then confirm:
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.
The last step is to add dummy, proxied (orange cloud) subdomain in the DNS tab, so the worker can pick it up:
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:
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!