URL Image

URL Shortener in 2 min using CloudFlare’s worker and KV.

Debjit Biswas

--

Time Required: 2 Min.

Ability: Able to copy past or a Full Stack developer :)- .

So this is my 2nd attempt to use CloudFlare's worker and Key-Value pair database.

Step 1

Create a KV database and a CloudFlare worker. You do not need any domain name for this, you can use the CloudFlare worker subdomain.

Now attach KV to your worker. Follow these steps on how to attach KV to your worker.

Open Worker > Settings > Variables > KV Namespace Bindings

Here you can give a custom name which will be available only from inside your worker and select your KV from the Dropdown List.

Step 2

In my case, I have named my KV “shortUrlList”. And how we are ready to use the code. So here is the code I am using inside worker to redirect.

addEventListener("fetch", (event) => {event.respondWith(handleRequest(event.request));});let fallBackUrl = "https://debjit.in";let url ;
async function handleRequest(request) {let getUrlSegment = request.url.split('/');
let codeForUrl = (getUrlSegment[getUrlSegment.length - 1] ?? 'base');if (codeForUrl.length !== 0 & codeForUrl !== null & codeForUrl !== undefined )
{
url = await shortUrlList.get(codeForUrl);
}
if( url === undefined|| url === null || url.length === 0 )
{
return Response.redirect(fallBackUrl, 301);
}
return Response.redirect(url, 301);
}

Here is a brief explanation of the code and how this work.

we get URL from the request and process inside, “codeForUrl” variable.

We search inside our KV using the key “shortUrlList.get(‘key”) and it returns the value or null/false.

Now simply return the URL with 301 or you can change it to 302.

This is very simple but if you wanted to add more URL redirection you have to log in to your CloudFlare account and then

Worker > KV > View >Add new Key Value Pair there.

Hope this works well for you.

--

--

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.