CORS
🔹 1. What is CORS?
Section titled “🔹 1. What is CORS?”- CORS = Cross Origin Resource Sharing.
- It’s a browser security feature that restricts requests from one origin(domain, protocol, port) to another.
- 👉 Example:
- Frontend (React) running on
http://localhost:3000. - Backend (Express API) running on
http://localhost:5000
- Frontend (React) running on
- By default, the browser blocks requests from frontend -> backend because they are different origins.
- CORS allows us to say :
- “This backend trusts requests from this frontend”.
🔹 2. Simple Example of the Issue
Section titled “🔹 2. Simple Example of the Issue”- Eg:
// Frontend (http://localhost:3000) fetch("http://localhost:5000/api/data") .then(res => res.json()) .then(data => console.log(data));- If the backend doesn’t allow it, the browser throws:
- Output:
Access to fetch at 'http://localhost:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy.🔹 3. Enabling CORS in Express
Section titled “🔹 3. Enabling CORS in Express”-
✅ Option 1: Using the
corsmiddleware (recommended).- Install
npm install corspackage. - Usage:
// Allow all origins (not recommended for production)app.use(cors());// Allow specific originapp.use(cors({origin: "http://localhost:3000"})); - Install
-
✅ Option 2: Manual headers (less common, more control)
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // allow only React app res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE"); res.header("Access-Control-Allow-Headers", "Content-Type, Authorization"); next(); });🔹 4. Preflight Requests (OPTIONS)
Section titled “🔹 4. Preflight Requests (OPTIONS)”- For
POST,PUT,DELETErequest, the browser sends a preflight OPTIONS request to check if the server allows it. corsmiddleware handles its automcatically.- If doing manually :
app.options('*", (req, res)=>{res.send(200)})
🔹 5. Security Best Practices
Section titled “🔹 5. Security Best Practices”- Don’t use
app.use(cors())with*in production. - Always restrict origin to trusted domains (like your frontend).
- Use
credentials: trueif sending cookies or tokens.
app.use(cors({ origin: "https://myapp.com", credentials: true }));✅ Summary
Section titled “✅ Summary”- CORS = allows controlled cross-origin requests.
- In Express → use
corsmiddleware (easy) or set headers manually. - Always restrict origins in production for security.