CORS & Helmet
Overview
If your React frontend lives on http://localhost:3000, and tries to fetch data from your Node API on http://localhost:8080, the browser will violently block the request and throw a CORS (Cross-Origin Resource Sharing) error. Browsers natively block scripts from requesting data from different domains to prevent malicious data theft. You must explicitly configure the backend to whitelist your frontend domain. Helmet is a separate, massive security library that automatically configures 15+ complex HTTP headers to protect against advanced browser attacks.
Syntax
// npm install cors helmet
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const app = express();
// --- 1. HELMET (General Security Headers) ---
// Instantly hides 'X-Powered-By: Express' (so hackers don't know your stack)
// Instantly blocks Clickjacking and MIME-sniffing
app.use(helmet());
// --- 2. CORS (Cross-Origin Resource Sharing) ---
// Define exactly which frontend domains are allowed to talk to this API
const corsOptions = {
origin: ['https://my-react-app.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allowed HTTP methods
credentials: true // MANDATORY if you are using HTTP-Only Cookies!
};
// Apply CORS globally before your routes!
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => res.send("Secure Data"));Common Pitfalls
- Using
app.use(cors())with no options in Production. This setsAccess-Control-Allow-Origin: *, meaning literally any website in the entire world can make API requests to your server and steal your data. You must strictly whitelist your frontend domains in theoriginarray. - The Preflight
OPTIONSrequest. Before sending a complexPOSTrequest, the browser automatically sends a hidden, emptyOPTIONSrequest to the server to ask 'Am I allowed to do this?'. If you apply CORS routing incorrectly, the preflight fails, and the actualPOSTrequest is never executed.
Interview Questions
Absolutely not. CORS is strictly a Browser Security mechanism. Postman and cURL do not care about CORS headers and will bypass them completely. CORS solely exists to protect the User's Browser from executing malicious JavaScript on rogue websites.
Real-World Example
How CORS looks at the raw HTTP Header level.
/*
The Request from the Browser:
Origin: https://my-react-app.com
The Response from the Express Server (configured by the CORS middleware):
Access-Control-Allow-Origin: https://my-react-app.com
Access-Control-Allow-Credentials: true
*/Check Your Knowledge
Test your understanding of CORS & Helmet with these quick questions.