Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Core worker code for url-forwarder based on Cloudflare Worker-KV
// This is the companion code for the linked blog
// https://blog.kmonsoor.com/on-edge-shortlink-server-cloudflare-kv-worker
// Please check the blog to get the context
// author : Khaled Monsoor (@kmonsoor)
// last updated: 25-May-2021
const failsafeURL = "https://kmonsoor.com" // replace it with yours ;)
const defaultStatusCode = 301 // standard HTTP code for redirection, don't change
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// console.log(request);
const requestURL = new URL(request.url);
if (requestURL.pathname === '/')
return Response.redirect(failsafeURL, defaultStatusCode);
const keySource = requestURL.pathname.substring(1);
// console.log(keySource);
const destinationURL = await GO_REDIRECTS.get(keySource);
// console.log(destinationURL);
if (destinationURL === null) {
// the message below can be updated as per your audience
return new Response("We couldn't find any such page", {status: 404})
}
else return Response.redirect(destinationURL, defaultStatusCode);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment