Skip to content

Instantly share code, notes, and snippets.

@kmonsoor
Created May 25, 2021 03:38
Show Gist options
  • Save kmonsoor/dc9f96660423c96471f8574ba018d867 to your computer and use it in GitHub Desktop.
Save kmonsoor/dc9f96660423c96471f8574ba018d867 to your computer and use it in GitHub Desktop.
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