Day 23/365 Your frontend is on localhost:3000 and your backend on localhost:8000.
Day 23/365 Your frontend is on localhost:3000 and your backend on localhost:8000. When you attempt a fetch request, you hit a CORS error. Why does this happen, and how do you resolve it?
🛑STOP! Don’t call it a ‘bug’ in your next interview.
If you’ve ever seen that red text in your console and felt like throwing your laptop, you aren’t alone. Here is the real reason it happens and how to explain it like a Senior Engineer.
THE “STRICT NEIGHBOR” ANALOGY
Think of the browser as a strict security guard at an apartment complex.
• The Frontend (:3000) wants to borrow data from The Backend (:8000).
• Because they live in different units (different ports), the guard stops the frontend.
• The guard won’t let the data pass unless the backend has explicitly placed the frontend on its “Trusted Guest List.”
TECHNICAL BREAKDOWN
CORS (Cross-Origin Resource Sharing) is a browser security layer. An “Origin” is the combination of Protocol + Domain + Port. Even if you are on the same machine, changing the port changes the Origin.
The Workflow:
1. Preflight (OPTIONS): The browser sends a secret “handshake” request to the backend first.
2. The Check: If the backend doesn’t respond with the Access-Control-Allow-Origin header, the browser blocks the actual data transfer to protect you from cross-site request forgery.
The Fix:
You must configure your server to explicitly whitelist your frontend origin.
• Example (Spring Boot): @CrossOrigin(origins = “
INTERVIEW FLEX
“CORS isn’t a bug; it’s a vital security guardrail. To fix it, we explicitly define allowed origins on the server. Pro tip: never use * (wildcard) in production—it bypasses security. Always whitelist your specific production domains to keep your API secure.”
Struggling with CORS in your latest project? Drop a comment with “Helpful” below and let me know which tech stack is giving you the most trouble! 👇
Follow @code_with_gary for daily system design & interview wins!
#tech #trending #explore #viral #fyp
Comments
Comments from the original post on Instagram
No comments yet
