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://.