Can't set headers on proxied redirect

needed_documentation
answered
#1

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
#2

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.

#4

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
#5

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
#6

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: