CORS ain't that complex, Understand it in 1 min

Saad KhaleeqSaad Khaleeq
2 min read

Alright, so you’re building a cool web app. Your frontend is running on http://localhost:3000 and your backend is running on http://localhost:8000. Seems fine, right? Both are on your machine. You try to fetch some data from your backend using fetch(), but suddenly you get this weird error in the browser console:

"Access to fetch at 'http://localhost:8000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy..."

And you're like... what?

Let me explain what’s going on here, in plain English.


The “Different Origins” Problem

Browsers are strict when it comes to security. If your frontend and backend don’t share the same origin, the browser gets suspicious. And by origin, it means the combination of:

  • Protocol (http or https)

  • Domain (like localhost or myapp.com)

  • Port (like 3000 or 8000)

So even though localhost:3000 and localhost:8000 are on the same machine, they’re treated as different origins.


What CORS Actually Is

CORS stands for Cross-Origin Resource Sharing. It’s basically a browser security feature. It prevents frontend code from accessing responses from a different origin unless that origin explicitly says it's okay.

In our example, your frontend (http://localhost:3000) is trying to talk to your backend (http://localhost:8000). The browser steps in and says, “Hey backend, do you trust this frontend enough to share your data?”

If the backend doesn’t reply with the proper CORS headers like:

httpCopyEditAccess-Control-Allow-Origin: http://localhost:3000

…then the browser blocks the response. That’s the CORS error you’re seeing.


How to Fix It (Briefly)

The fix usually involves changing something in your backend code. For example, in Express (Node.js), you'd do something like:

const cors = require('cors');
app.use(cors({ origin: 'http://localhost:3000' }));

This tells the backend: “Hey, allow requests from this specific frontend origin.”


Summary

CORS isn't a bug. It's a browser's way of protecting users. Once you understand the whole "different origin" thing, it makes a lot more sense.

If you ever run into a CORS error, don’t panic as it’s a trust issue, and your backend needs to give the frontend permission to connect.

0
Subscribe to my newsletter

Read articles from Saad Khaleeq directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saad Khaleeq
Saad Khaleeq

Creative. Fast Learner. Super Passionate. Highly Enthusiastic.