Mid-level (2-5 years)Node.js

How do you secure a Node.js Express API?

Quick answer

Validate all input, use parameterised queries, add security headers with helmet, rate-limit requests, restrict CORS, hash passwords, keep secrets in environment variables, and keep dependencies updated and audited.

Input: validate and sanitise every body, query and parameter with a schema library such as Zod or Joi, and never build SQL or shell commands by string concatenation, which prevents injection. Output: do not send stack traces or internal error messages to clients.

Transport and headers: use HTTPS, set helmet() for secure headers, configure CORS to allow only your own origins, and set cookies as HttpOnly, Secure and SameSite. Abuse: add rate limiting (for example express-rate-limit), limit request body size and add stricter limits on login and password reset endpoints. Operations: store secrets in environment variables or a secret manager, run npm audit, pin dependency versions with a lock file, run the process as a non-root user and log security events.

import helmet from "helmet";
import rateLimit from "express-rate-limit";
import cors from "cors";

app.use(helmet());
app.use(cors({ origin: ["https://www.example.com"] }));
app.use(express.json({ limit: "100kb" }));
app.use("/api/login", rateLimit({ windowMs: 15 * 60 * 1000, max: 10 }));