Hi, @vcamp. This isn’t a bug as this is expected behavior. I’ll do my best to explain why (and there is a solution at the end).
The background function never returns content to the browser so you will never be able to return customer headers being set inside the function invocations. You can never fix CORS headers using headers returned by background functions because the never reply directly to the browser. Because they never reply directly to the browser there is no way to include a custom header from the function itself.
The background function documentation says this:
These longer-running functions are processed as background tasks through AWS Lambda using asynchronous invocation. This means that when a function is invoked, it’s added to a queue instead of being processed immediately. There is an initial
202 success response when a function is queued.
Our systems send a 202 status and the function itself never replies to the browser.
- I expected the function would not actually be triggered if browser says
CORS error (but it is triggered).
The function invocation has no way of detecting the CORS error in the browser. It only sees the HTTP request and that queues the function invocation.
The background function cannot know about the CORS errors from the browser because there is no communication between the two.
- With background functions:
CORS error shows in the browser regardless of any
Access Control Allow Origin header in the function.
The comment above assumes the headers are sent but that isn’t happening in reality. There are no custom headers being sent with a background function response because the background function never sends a response to the browser.
BUT WAIT! THERE IS A SOLUTION! (*insert snappy Netlify advertisement song here*)
The recommended solution for this would be to proxy to the other function so the function invocation appears to be happening on the first domain from the browser’s point of view. For example, you might put this in
https://otherdomain.com/api/background/* https://example.com/.netlify/functions/:splat 200!
If you called this URL:
with that redirect above active, it would (invisibly to the browser) proxy that request to this URL:
This will avoid the CORS error because the domain will match in the browser but, behind the scenes at Netlify, you will still be calling the background function on the other domain.
If that doesn’t fix the issue or if there are any other questions, please let us know.