Node.js – Security
Rules
- Never log passwords, tokens, or PII
- Store secrets only in environment variables — never in code or git
- Sanitize all user inputs to prevent injection attacks
- Set security headers with helmet middleware
- Rate-limit all public endpoints
- Use parameterized queries — never string-interpolate SQL
Essential Middleware
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
app.use(helmet());
app.use(rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
}));
Parameterized Queries
// Correct
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
// Incorrect — SQL injection risk
const user = await db.query(`SELECT * FROM users WHERE id = ${userId}`);
Environment Variables
// Correct
const dbPassword = process.env.DB_PASSWORD;
// Incorrect
const dbPassword = 'mysecretpassword';