netlify / edge-functions-examples

Explore a library of reference examples for learning about Edge Functions on Netlify.
https://edge-functions-examples.netlify.app/
70 stars 29 forks source link

Unable to set Custom Response header via edge function #34

Open kriordan37 opened 2 years ago

kriordan37 commented 2 years ago

Following the documentation I was able get the hello world edge function running and to verify it via the netlify cli. However when I switch out the body of the test.ts file with response edge function to:

import type { Context } from "https://edge.netlify.com";

export default async (request: Request, context: Context) => {
  const url = new URL(request.url);

  if (url.searchParams.get("method") !== "set-response-header") {
    return context.next();
  }

  context.log(`Adding a custom header to the response for ${url}`);

  const response = await context.next();
  response.headers.set("X-Your-Custom-Header", "Your custom header value");
  return response;
};

and update the netlify.tomi to

[[edge_functions]] 
path = "/*"
function = "hello"

I can see that the edge function is◈ Loaded edge function hello up via the --edgeInspect flag, but when inspected the page I do not see the reponse header. Connecting the debugger doesn't lead to much helpful information that I can see.

kriordan37 commented 2 years ago

I also tried seperating it exactly how it is in this repo. so i created a file for the response function called `set-response-header.ts' and added to my netlify.toml

[[edge_functions]]
  path = "/test"
  function = "hello"

[[edge_functions]]
  function = "set-response-header"
  path = "/*"

the /test page is working but no where on the site am i getting the custom response header

kriordan37 commented 2 years ago

I was able finally get a custom header added in one place but its not site wide.

I commented out this section of the set-response-header.ts

  /*if (url.searchParams.get("method") !== "set-response-header") {
    return context.next();
  }*/

because url.searchParams.get("method") was returning null and the code wasn't getting passed this.

my netlify tomi now looks like this

[[edge_functions]]
  function = "set-response-header"
  path = "/*"

[[edge_functions]]
  path = "/test"
  function = "hello"

however when inspecting the page I only see the custom header on the /test page and no where else

kriordan37 commented 2 years ago

i made a mistake and am now seeing the headers on responses. however it only works when ignoring url.searchParams.get("method")