Hey devs 👋! Have you ever built a frontend that talks to a backend API, and everything works locally... but suddenly, when deployed, the browser screams at you with:

Access to fetch at 'https://yourapi.com' from origin 'https://yourfrontend.com' has been blocked by CORS policy 😱

Yep. That’s CORS in action.

Let’s break it down.


🧠 What is CORS?

CORS stands for Cross-Origin Resource Sharing. It’s a browser security feature that restricts how web pages loaded from one origin can request resources from another origin.

🧪 Example:

Your frontend is hosted at https://myfrontend.com and your backend API is at https://myapi.com. Even though they both belong to you, the browser considers this a cross-origin request.

CORS helps prevent malicious sites from making unauthorized requests on behalf of users to other origins (a.k.a. CSRF attacks).


🔒 Why CORS is Important

Without CORS, any website could make requests to your API using a logged-in user's credentials. That would be a major security issue.

CORS gives you control over which origins can interact with your API. It's like putting a guest list at the door to your backend party 🎉.


⚙️ How CORS Works

When a browser detects a cross-origin request, it sends a preflight request (an HTTP OPTIONS request) to the server. The server must respond with headers like:

Access-Control-Allow-Origin: https://myfrontend.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type

If the response looks good, the browser proceeds. If not, it blocks the request.


🚀 Implementing CORS in Node.js (with Express)

Node.js + Express makes it super easy using the cors middleware.

✅ Basic Setup:

npm install cors
const express = require('express');
const cors = require('cors');

const app = express();

// Allow all origins (not recommended for production)
app.use(cors());

// OR allow specific origins
app.use(cors({
  origin: 'https://myfrontend.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type'],
}));

app.get('/api/data', (req, res) => {
  res.json({ message: 'CORS works!' });
});

app.listen(3000, () => console.log('Server running on port 3000'));

🐍 Implementing CORS in FastAPI (Python)

FastAPI has first-class support for CORS via the fastapi.middleware.cors module.

✅ Basic Setup:

pip install fastapi uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Allow specific origin
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://myfrontend.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

@app.get("/api/data")
def read_data():
    return {"message": "CORS works!"}

🔧 Best Practices

  • Always specify exact origins in production instead of using *
  • Restrict methods and headers to what’s needed
  • 🚫 Never allow credentials with wildcard origins
  • 🔒 Test with real frontend domains before going live

🧵 TL;DR

  • CORS is a security feature that prevents unauthorized cross-origin requests.
  • Browsers enforce it, not your backend by default.
  • You need to explicitly allow origins that can access your APIs.
  • Node.js (Express) and FastAPI both make it easy to configure CORS.

If you’ve ever hit that scary CORS error, you now know it’s not a bug — it’s your browser trying to protect users. Respect it. Configure it. And ship securely 💪

Got questions or a CORS horror story? Drop them in the comments 👇

Happy coding, friends! ✌️