CORS Header not being applied

Hi, I’m using express js to handle netlify functions. I need to apply cors rules to all responses so my main site can make requests.

I added this to my netlify.toml file, but no CORS header is being sent.

[[headers]]

Define which paths this specific [[headers]] block will cover.

for = “/*”
[headers.values]
Access-Control-Allow-Origin = “https://mysite.com

I’ve also tried using cors middleware in app.js but I’m not getting any results.

Is there anything else I need to be doing? Thanks

Netlify Functions return their own headers and are unaffected by the headers you set here.

So, you could do something like:

return {
  statusCode: 200,
  body: JSON.stringify('Hello'),
  headers: {
    'Access-Control-Allow-Origin': 'value'
  }
}

Is there any way to set this header for all responses. Keeping in mind I’m using serverless-http to export my functions, so from the outside, it’s just a standard node app.

As I said, headers for serverless functions are defined within functions. You could create a separate file like:

functions/intermediate/headers.js with the content:

const headers = {
  'Access-Control-Allow-Origin': 'value'
}

module.exports = {
  headers
}

In your function:

const headers = require('./intermediate/headers).headers

// rest of the stuff
return {
  statusCode: 200,
  body: JSON.stringify('Hello'),
  headers
}