Free URL shortener with Cloudflare Workers

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})
}

How to get it working

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

--

--

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
Lucjan Suski

Lucjan Suski

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