Here’s Exactly How To Resolve CORS Errors In Your Fetch Calls
And how never to run into a CORS error again.
Have you ever wondered why you get CORS errors in your React (web) app but never in Postman or another API platform?
CORS errors are probably the most annoying problem you can run into.
They quickly drain your energy and patience and you might be able to fix it by copying and pasting code you find on Stack Overflow, after having lost 2 hours trying every headers possibility.
But the key to resolving CORS errors is simply understanding how it works once and for all.
I guarantee you by the end of this article, you’ll understand CORS and never run into this error again.
Why you don’t get CORS errors in Postman
If you run a fetch call to an endpoint URL on another external domain, you’ll get a CORS error.
But run the same request from Postman or another API invocation tool and you won’t get that CORS error.
Why is this?
Well, browsers implement CORS to protect users by restricting requests from unauthorized origins.
The underlying engine inside your browser enforces this protection. In contrast, an API tool like Postman directly makes HTTP requests from your device without involving a browser rendering engine. Essentially it does not adhere tp browser-enforced CORS policies.
Additionally, when performing a fetch request, your browser performs a “preflight” check to ask the server if the origin is allowed.
Consequently, if the server does not provide the correct headers, the request fails with what is known as a CORS error.
Critically, the headers provided on your API must match the server’s headers response.
Postman skips this process entirely and sends the request without the preflight validation.
Providing these headers is the key to solving CORS errors…
Solving CORS Errors
Now that we understand that CORS errors happen because the headers on the server’s response are incorrect or do not match that of the browser’s request, we can fix our CORS issues by ensuring the response and request headers match.
Let’s look at an example to best understand this.
Imagine you create server-side code to write an item to your database.
Here I’ll be using an example of a serverless AWS Lambda function that will return some data, using API Gateway to configure CORS.
I can write the following server code:
export const handler = async (event) => {
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': '*'
},
body: JSON.stringify({ message: "Hi from Lambda!" }),
};
}
My server response is saying, this server function will:
Accept requests from any (*) origin
Allow the POST and OPTIONS methods only
Allow headers from any (*) origin
Now in the CORS configuration on my API, I must set the exact same access control configuration.
Here’s an example from an API Gateway HTTP API:
In this CORS configuration, I have set the matching headers as on my server-side response.
The Access-Control-Allow-Origin must be equal to *.
The Access-Control-Allow-Headers must be equal to *.
The Access-Control-Allow-Methods must be equal to POST and OPTIONS.
With these matching configurations, when the browser will make a fetch request, the request headers will perfectly match the server’s response headers.
This is what the browser engine will validate. When the request matches the response, the browser allows the request, and the fetch call will succeed.
If there is a discrepancy between my request and the server’s response, that’s when I get a CORS error.
Summary
To summarize, CORS errors occur in the browser because they enforce strict security rules that require requests to be made from authorized origins only.
API tools like Postman entirely bypass these policies and allow you to easily test and run endpoint URLs.
To avoid CORS errors, you must make your browser’s request headers precisely match your server’s response headers.
👋 My name is Uriel Bitton and I’m committed to helping you master Serverless, Cloud Computing, and AWS.
🚀 If you want to learn how to build serverless, scalable, and resilient applications, you can also follow me on Linkedin for valuable daily posts.
Thanks for reading and see you in the next one!