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! βοΈ
Top comments (0)