Debugging Pages function with KV

I made a simple function in “functions/![link].js” file:

export async function onRequestGet(context) {
  let originUrl = (new URL(context.request.url)).origin;
  if (context.params !== undefined) {
    if ( !== undefined) {
      let req =;
      let link = await context.env.CfUrlShortener.get(req);
      if (link) {
        return new Response(null, {
          headers: { Location: link },
          status: 301,
      else {
        return new Response(null, {
          headers: { Location: originUrl },
          status: 301,
  return new Response("ERROR NO SHORT LINK PROVIDED", null, 2);

The routes are correctly created by CF:

  "routes": [
      "routePath": "/!:link",
      "method": "GET",
      "module": [
  "baseURL": "/"

I also bind my KV namespace in Pages

Locally it works perfectly with:

npx wrangler pages dev --kv CfUrlShortener --binding __DEBUG__="1" \
         -- npm run serve 

But If I deploy it to CF I get a wonderfull

The message tells me to check the error log… but where is it ?

I see the error

The KV namespace is called “CfUrlShortner” however you have the binding set to “SHORTURL” in your screenshot. Change that to context.env.SHORTURL and it should work fine.

Also, you can just do Response.redirect(link, 301), no need to make the response and set Location header yourself :slight_smile:

1 Like

Thanks a lot… I made the mistake because [email protected] 0.0.25 does not connect to my real KV namespace, so it works locally by creating a .mf/kv… directory.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.