Node.js apps are frequent targets of attacks like XSS, CSRF, SQL Injection, NoSQL Injection, JWT spoofing, etc. A secure Node.js app involves not just secure code, but also proper headers, tokens, input validation, encryption, and session management.
| Threat | Description |
|---|---|
| XSS | Attacker injects JavaScript into client-facing pages |
| CSRF | Cross-site request triggering user actions without consent |
| NoSQL Injection | Attackers manipulate queries in MongoDB, etc. ({ "$gt": "" }) |
| JWT Spoofing | Unsigned or weakly signed tokens allow forgery |
| Prototype Pollution | Attacker changes object prototype chain using user inputs (__proto__) |
Set security headers:
const helmet = require('helmet');
app.use(helmet());
Use a schema validator like:
const Joi = require('joi');
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).required(),
});
// Dangerous:
User.find({ email: req.body.email });
// Better:
const email = sanitize(req.body.email); // or use a whitelist-based filter
const token = jwt.sign(payload, process.env.JWT_SECRET, {
algorithm: 'HS256',
expiresIn: '1h',
});
Never use none algorithm, and always verify tokens with proper expiration and audience.
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);