Create a URL Shortener for personal use using CloudFlare worker in 5 min.

Debjit Biswas
2 min readMay 15, 2022

I was forwarding a bit-ly to my colleague and this stupid idea hit me. We both are full -f*king stack developers and solve some really good problems. But why we are using 3rd party software for shortening the links?

I started googling and found a somewhat usable script with no documentation and very bad usage of naming scheme, (like me 2 years ago).

I tested and updated some more to it and called it mine. :).

So, my domain DNS is hosted on Cloudflare, so I tried Cloudflare worker first and the js code works.

Here is the Idea, I will add a key-value pair with the key as a short name and the value is URL when the key is matched forward to the URL with 301. So simple.

Now it’s time to make changes. so here is the full code. The code is self explanatory.

const shortLinks = [{ key: 'github', value: 'https://github.com/debjit' },{ key: 'gh', value: 'https://github.com/debjit' },{ key: 'linkedin', value: 'https://www.linkedin.com/in/debjitwb/' },{ key: 'ld', value: 'https://www.linkedin.com/in/debjitwb/' },{ key: 'twitter', value: 'https://twitter.com/debjit012' },{ key: 'tw', value: 'https://twitter.com/debjit012' },]// This is default fallback URLconst fallbackUrl = "https://debjit.in";addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));})/*** Respond with a hello worker text* @param {Request} request*/async function handleRequest(request) {let getUrlSegment = request.url.split('/');let res = matchReq(getUrlSegment[getUrlSegment.length - 1],shortLinks);if (res === null) {return Response.redirect(fallbackUrl, 301);}return Response.redirect(res, 301);}function matchReq(part,shortLinks) {const result = shortLinks.find( ({ key }) => key === part );if (result) {return result.value;}return null;}

Now you can add many URLs as key-value pairs.

Now it is time to set up the Cloudflare worker to redirect when a link is found but go to the fallback URL when no error is found.

Cloudflare Dashboard > Workers > Overview > Create a Service > Give service a name >Create Service >Quick Edit > Paste the code and save.

It is time to add a custom domain to the worker.

Worker name > Custom Domains > Add domain name.

That's it. My DNS is hosted in CloudFlare so it will update internally, you do not have to do anything. We have a static fast link shortener subdomain that is ready.

Now share the link, if there is no link it will go to fall back URL, no registration no 3rd party site consuming your data.

--

--

Debjit Biswas

I am a Web Developer. I love to do experiments and share my journey with you. Please follow me for more posts. Go to https://debjit.in for more info.