Redirects using KV to store redirect map

Then store like:

key1

{ "code": 410 }

key2

{ "dest": "https://test.com/test/", "code": 301 }

code:

const handleRequest = async (request) => {
  const requestURL = new URL(request.url);
  const keySource = requestURL.pathname;
  const { dest, code } = await KV_REDIRECT_MATRIX_BIND.get(keySource, "json");
  if (code === 301) {
    return Response.redirect(dest, code);
  } else if (code === 410) {
    return new Response("Gone", { status: 410, statusText: "Gone" });
  }
  return fetch(request);
};

addEventListener("fetch", (event) =>
  event.respondWith(handleRequest(event.request))
);
2 Likes