Can't set headers on proxied redirect

You can’t set a header on a proxied redirect.

[[redirects]]
  from = "/api/*"
  to = "https://api.example.com/:splat"
  status = 200
  headers = {Access-Control-Allow-Origin = "*"}

This doesn’t work, although the docs say it should:

The redirect works, but the CORS header isn’t added.

Adding a headers block just for this route also doesn’t work:

[[headers]]
  for = "/api/*"
  [headers.values]
  Access-Control-Allow-Origin = "*"

However interestingly if you apply this rule to everything:

[[headers]]
  for = "*"
  [headers.values]
  Access-Control-Allow-Origin = "*"

The header gets set on static pages served by Netlify.

However proxied redirects don’t get the header.

This is causing issues for me because I can’t use my API endpoint for development or prerendering without a CORS header.

2 Likes

I also found this: https://github.com/seansaleh/netlify-proxy-headers

So it seems like people have been having issues with this for a while.

Hey luke, thanks for pointing this out. We will take a closer look and get back to you when we have had a chance to look through this. :+1:

1 Like

Ok so for anyone else who ends up here, the redirects syntax:

[[redirects]]
  from = "/api/*"
  to = "https://api.example.com/:splat"
  status = 200
  headers = {Access-Control-Allow-Origin = "*"}

is for setting a request header sent to the remote server, not a response header returned to the client.

That makes sense, and it is clear in the docs, I just misinterpreted it.

As for the headers syntax:

[[headers]]
  for = "/api/*"
  [headers.values]
  Access-Control-Allow-Origin = "*"

I still think this should work, but it seems like Netlify just doesn’t support injecting headers into proxied requests.

It would be good if that was made clear in the docs, or even better, if Netlify could add support for injecting headers to proxied requests.

1 Like

thanks for continuing to work on this - and for coming back and taking the extra step and writing this out for the next person to benefit. :clap:

I’ve pinged the docs team and asked them to take a look :+1:

Hey Luke!

Sorry to reopen this thread a lot later, but I just saw it and wanted to set the record straight:

Custom headers only apply to files we serve from our own backing store.

If we proxy to a different service, we do not add any headers EXCEPT a few administrative ones - we do not intend to let you add your own headers to what gets returned to the browser. While I realize this isn’t what you were hoping for, the intention is that you’d set those headers yourself on the REMOTE service. I understand that’s not always possible, but that’s how the feature was designed.

Thanks again for talking through this and we will try to make this clearer in the docs!