What is CORS?
Cross-Origin Resource Sharing. It is a security feature on the browser that enables the browser to protect resources on another origin being called from one origin.
It is simple yet debugging it sometimes is cumbersome, mostly because of a lack of understanding of CORS. One big thing that I missed when dealing with Cors error is that Cors security flags are controlled from the backend and they are just response headers.
Let me give you an example.
Origin here is the URL, which we are requesting on browser.
Example Scenario 1: Your app at example.com
calls api.example.com
. If the server allows requests from example.com
(as specified in CORS headers), all are smooth—no errors.
Example Scenario 2: Now, picture your app example.com
reaching out to blabla.com
. Server blabla.com has response headers saying that requests are only allowed from the same origin. The browser blocks the interaction, ensuring a secure barrier against unauthorized cross-origin requests.
Example Scenario 3: Now, picture your app example.com
reaching out to blabla.com
. Server blabla.com has response headers like this
Access-Control-Allow-Origin: *
This means that any origin is allowed so the request won't be blocked. Similarly, there are other headers like Access-Control-Allow-Headers(Block unnecessary headers from the browser).
Example CORS Middleware with Golang
This will write these headers to every request.
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Allow cross-origin requests from any domain
w.Header().Set("Access-Control-Allow-Origin", "*")
// Allow the Content-Type header for POST requests
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// Allow GET, POST, and OPTIONS methods
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
// If it's a preflight request, return immediately with a 200 status code
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
// Continue to the next handler in the chain
next.ServeHTTP(w, r)
})
}
router.use(cors)
Debugging CORS Error
Whenever you are facing a CORS error on your app, go to console logs in the browser dev tool and check which policy is blocking that request. Change the response header from your backend and walahhh, the issue will be resolved.
Happy Coding 🤓