DEV Community

M Inam
M Inam

Posted on

🚧 Understanding CORS: Cross-Origin Resource Sharing for Web Developers

If you’ve seen this in your console:

“Access to fetch at ‘https://api.example.com’ from origin ‘https://yourapp.com’ has been blocked by CORS policy…”

You’re not alone. Let’s dive into what CORS is, why it exists, and how to fix it.

🌍 What is CORS?

CORS (Cross-Origin Resource Sharing) is a browser-enforced security feature that prevents your frontend app (served from one origin) from accessing resources from another origin unless explicitly allowed by the server.

This behavior stems from the Same-Origin Policy, which is designed to help prevent cross-site attacks.

🧪 How CORS Works

When your frontend makes a request to another origin, the browser sends an Origin header:
Origin: https://myapp.com

If the server responds with:
Access-Control-Allow-Origin: https://myapp.com
The browser proceeds. Otherwise, it blocks access to the response.

🛡️ Preflight Requests

For requests using methods like POST, PUT, or custom headers, the browser sends a preflight OPTIONS request to check if it’s safe.

If the server doesn’t respond correctly, the browser cancels the actual request.

🔧 Backend Config: Enabling CORS

Here’s how to configure CORS in common backend frameworks:

🟢 Express.js
const cors = require('cors');
app.use(cors({
origin: 'https://myapp.com',
credentials: true
}));

🐍 FastAPI
`from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com"],
allow_credentials=True,
allow_methods=[""],
allow_headers=["
"],
)`

❗ Common CORS Issues

  • ❌ Missing Access-Control-Allow-Origin header
  • ❌ Wildcard origin (*) used with credentials
  • ❌ Server doesn’t respond to OPTIONS preflight

🧠 Dev Tips
Use browser dev tools to inspect request/response headers.

Use tools like http-proxy-middleware or Vite’s proxy config during local development.

Never disable CORS in production — configure it properly.

✅ Final Thoughts

CORS is not a bug — it’s a feature 🔐

Understanding how it works makes you a more confident full-stack developer and prevents hours of frustrating debugging.

💡 Got a CORS horror story or a helpful trick? Share it in the comments 👇

Top comments (0)