Protect HTTP
- helmet — sets security headers in one line:
app.use(helmet()) - cors — allow only your own frontend domains, not
*, for private APIs - express-rate-limit — limit requests (especially login and OTP routes) to stop brute force
- Always use HTTPS in production
- Hide the
X-Powered-Byheader (helmet does this)
Validate and sanitise input
- Validate every
req.body,req.paramsandreq.query(zod, joi, express-validator) - Limit body size:
express.json({ limit: '100kb' })
Injection
- SQL: always use
?placeholders - NoSQL: never pass raw objects from requests into MongoDB queries —
{ "$gt": "" }can bypass a password check - Never use
eval()or run shell commands with user input
Secrets and dependencies
- Keep secrets in environment variables
- Hash passwords with bcrypt or argon2
- Run
npm auditand update packages regularly; remove unused ones
Errors
Don't leak stack traces; set NODE_ENV=production.
Example
Example — A secure Express setup
JavaScript
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
const app = express();
app.use(helmet());
app.use(cors({ origin: ['https://agyanadda.com'], credentials: true }));
app.use(express.json({ limit: '100kb' }));
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
limit: 5, // 5 attempts per IP
message: { error: 'Too many login attempts. Try again later.' },
});
app.post('/api/login', loginLimiter, async (req, res) => {
const email = String(req.body.email ?? ''); // force string: blocks {"$gt": ""} tricks
const password = String(req.body.password ?? '');
// ... look up user with email, check bcrypt.compare(password, hash)
res.json({ ok: true });
});
app.listen(3000);
// Terminal: check dependencies for known vulnerabilities
// npm audit
// npm audit fix
helmet adds headers such as Content-Security-Policy, CORS allows only agyanadda.com, and the sixth login attempt within 15 minutes gets a 429 Too Many Requests response.