Concept:

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.


Core Threats to Know:

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__)

Best Practices Checklist:

Use Helmet

Set security headers:

const helmet = require('helmet');
app.use(helmet());

Input Validation (Never Trust the Client)

Use a schema validator like:

const Joi = require('joi');
const schema = Joi.object({
  email: Joi.string().email().required(),
  password: Joi.string().min(8).required(),
});

Sanitize Inputs (Avoid NoSQL Injection)

// Dangerous:
User.find({ email: req.body.email });

// Better:
const email = sanitize(req.body.email); // or use a whitelist-based filter

Use Strong JWT Practices

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.

Hash Passwords (NEVER store raw)

const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);