REST API Masterclass
Architecting Modern Backends01.Home02.What is REST?03.HTTP Deep Dive04.URI Best Practices05.JSON & Data Formats06.Environment Setup07.Your First Resource08.Advanced Controllers09.Database Strategy10.JWT Authentication11.Role-Based Auth (RBAC)12.API Versioning13.Filtering & Searching14.Pagination & Sorting15.Global Error Handling16.Rate Limiting17.CORS & Security18.Swagger & OpenAPI19.Testing with Supertest20.Webhooks & Caching21.Production Checklist
CORS & Security
Security is not a feature; it is a fundamental requirement. Because APIs often serve data to different domains, CORS is your first security hurdle.
1. Understanding CORS
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that prevents a web page from making requests to a different domain than the one that served the page.
# Example: Frontend on localhost:3000 -> Backend on localhost:5000
# The Browser will send a "Preflight" OPTIONS request to check permissions.2. Configuring CORS
Be specific. Never use origin: "*" in production.
const cors = require('cors');
const corsOptions = {
origin: ['https://www.yourdomain.com', 'https://admin.yourdomain.com'],
methods: 'GET,POST,PUT,DELETE',
credentials: true
};
app.use(cors(corsOptions));3. Security Headers (Helmet.js)
Helmet helps secure your Express apps by setting various HTTP headers. It protects against XSS, Clickjacking, and other common attacks.
const helmet = require('helmet');
app.use(helmet());4. Data Sanitization
Always sanitize user input to prevent NoSQL Injection orCross-Site Scripting (XSS) if you return that data to a UI.
Pro Pattern: Use HSTS (HTTP Strict Transport Security) to tell browsers that they should only communicate with your API over HTTPS, even if the user typed
http://.