Node.js ยท Chapter 38 of 43

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.

Example 1 (javascript)
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.

Example 2 (javascript)
npm audit
Output
found 0 vulnerabilities

npm 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.
๐Ÿ’ก Note: Keep dependencies updated; many vulnerabilities are fixed quickly upstream.

๐Ÿ“ Quick Quiz

1. What does the helmet middleware do?

2. What command checks for known vulnerabilities in dependencies?

3. Where should secrets like API keys be stored?