Security Basics
Security in Node.js apps involves protecting against common vulnerabilities: injection attacks, exposed secrets, outdated dependencies, and insecure defaults.
Tools like `helmet` add sensible security-related HTTP headers automatically, and `npm audit` scans dependencies for known vulnerabilities.
Common risks
SQL/NoSQL injection, cross-site scripting (XSS), exposing stack traces, and hardcoded secrets are among the most common Node.js security mistakes.
Using helmet
The `helmet` middleware sets HTTP headers that guard against clickjacking, MIME sniffing, and other common attacks with one line of code.
const helmet = require('helmet');
const express = require('express');
const app = express();
app.use(helmet());helmet() adds multiple protective HTTP headers with a single middleware call.
npm auditfound 0 vulnerabilitiesnpm audit checks installed dependencies against a database of known vulnerabilities.
Key points
- Validate and sanitize all user input.
- Use helmet() for safer default HTTP headers.
- Run npm audit regularly to catch vulnerable dependencies.
- Never hardcode secrets โ use environment variables instead.
