Security Best Practices
Hardening an Express app for production - secure headers with Helmet, rate limiting, CORS done correctly, and the most common Express security mistakes.
What it is, in plain English: Security in Express means defending against the common attack patterns every public web server faces: setting secure HTTP headers (Helmet), limiting how many requests a client can make (rate limiting), correctly restricting which origins can call your API (CORS), and following the general JavaScript security principles -- input validation, output escaping, never trusting client data -- applied specifically to a server context.
Hardening a server before it goes live
Helmet -- secure headers in one line
// npm install helmet
import helmet from "helmet";
app.use(helmet());
// Sets ~11 security-related HTTP headers automatically:
// X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security,
// Content-Security-Policy, Referrer-Policy, and more.
// This single line is the highest-value, lowest-effort security improvement
// you can make to any Express app.Rate limiting -- stopping abuse
// npm install express-rate-limit
import rateLimit from "express-rate-limit";
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minute window
max: 100, // max 100 requests per IP per window
message: "Too many requests, please try again later",
});
app.use(limiter); // applies globally
// Stricter limits on sensitive routes (login is a common brute-force target):
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5, // only 5 login attempts per 15 minutes
});
app.post("/login", loginLimiter, loginHandler);CORS -- controlling who can call your API
// npm install cors
import cors from "cors";
// ✗ Allowing everyone (only OK for fully public APIs):
app.use(cors()); // Access-Control-Allow-Origin: *
// ✓ Restricting to known origins (almost always what you want):
app.use(cors({
origin: ["https://myapp.com", "https://admin.myapp.com"],
credentials: true, // allow cookies to be sent cross-origin
}));
// Per-route CORS (different rules for different endpoints):
app.get("/public-data", cors(), handler); // open
app.get("/private-data", cors({ origin: "https://myapp.com" }), handler); // restrictedThe basic security checklist
// 1. app.use(helmet()) -- secure headers
// 2. app.use(rateLimit({...})) -- prevent abuse
// 3. app.use(cors({ origin: [...] })) -- restrict cross-origin access
// 4. Validate ALL input (see Validation page)
// 5. Never log sensitive data (passwords, tokens, card numbers)
// 6. Use HTTPS in production (terminate TLS at a load balancer or use Let's Encrypt)
// 7. Keep dependencies updated -- npm audit regularly
// 8. Store secrets in environment variables, never in code
Try It Yourself (Node.js logic)
Official Sources
- Express.js — Security Best Practices
- Helmet Documentation
- OWASP Top 10
- express-rate-limit Documentation
The Codex links only to official documentation. No third-party tutorials.