Web & Network6 min readLast updated: Mon Apr 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

CORS Explained: Why is it blocking my API?

You build a frontend on localhost:3000. You build an API on localhost:4000. You try to fetch data.
Error: Access to fetch has been blocked by CORS policy.

What is CORS?

Browsers have a security rule called the Same-Origin Policy.
It says: "A website on Domain A cannot talk to Domain B unless Domain B explicitly allows it."

This prevents BadSite.com from making a request to YourBank.com in the background while you are logged in.

How to fix it

You cannot fix CORS on the frontend (Client). You must fix it on the Server.
The server must send a specific header:

Access-Control-Allow-Origin: * (Allow everyone)
OR
Access-Control-Allow-Origin: https://frontend.com (Allow only my frontend)

Preflight Requests (OPTIONS)

For complex requests (like sending JSON or using DELETE), the browser sends a tiny "Preflight" request first.

  1. Browser: "Hey Server, are you okay with me sending a DELETE request?" (OPTIONS method)
  2. Server: "Yes, I allow DELETE." (204 No Content)
  3. Browser: "Okay, here is the real request."