DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

CORS Errors Explained: Why Your Fetch Fails and How to Fix It

"Blocked by CORS policy" is the most Googled frontend error. It is a browser protection, not a server bug, and the fix always lives on the server.

What CORS actually does

Browsers block JS from reading responses from another origin unless the server opts in with Access-Control-Allow-Origin.

Preflight requests

Non-simple requests (custom headers, JSON content type, PUT/DELETE) trigger an OPTIONS preflight. If the server does not answer it with the right Allow-Methods and Allow-Headers, the real request never fires.

Common mistakes

  1. * together with credentials: not allowed. Echo the specific origin and set Allow-Credentials: true.
  2. Setting headers only on success responses; errors (401, 500) must include them too.
  3. Forgetting Vary: Origin when the allowed origin is dynamic, which poisons caches.
  4. Trying to fix it from the client with mode: 'no-cors'. That gives you an unreadable opaque response.

Dev tip

Use a dev proxy instead of disabling security in the browser.

Generate the headers

For a quick correct config I use the free CORS generator, which runs in the browser.

More tools: webdevtoolbox.com.

Top comments (0)