agyanadda@gmail.com

Node.js Security Best Practices

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 28 of 30

Protect HTTP

  • helmet — sets security headers in one line: app.use(helmet())
  • cors — allow only your own frontend domains, not *, for private APIs
  • express-rate-limit — limit requests (especially login and OTP routes) to stop brute force
  • Always use HTTPS in production
  • Hide the X-Powered-By header (helmet does this)

Validate and sanitise input

  • Validate every req.body, req.params and req.query (zod, joi, express-validator)
  • Limit body size: express.json({ limit: '100kb' })

Injection

  • SQL: always use ? placeholders
  • NoSQL: never pass raw objects from requests into MongoDB queries — { "$gt": "" } can bypass a password check
  • Never use eval() or run shell commands with user input

Secrets and dependencies

  • Keep secrets in environment variables
  • Hash passwords with bcrypt or argon2
  • Run npm audit and update packages regularly; remove unused ones

Errors

Don't leak stack traces; set NODE_ENV=production.

Example

Example — A secure Express setup JavaScript
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';

const app = express();

app.use(helmet());
app.use(cors({ origin: ['https://agyanadda.com'], credentials: true }));
app.use(express.json({ limit: '100kb' }));

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,   // 15 minutes
  limit: 5,                   // 5 attempts per IP
  message: { error: 'Too many login attempts. Try again later.' },
});

app.post('/api/login', loginLimiter, async (req, res) => {
  const email = String(req.body.email ?? '');      // force string: blocks {"$gt": ""} tricks
  const password = String(req.body.password ?? '');
  // ... look up user with email, check bcrypt.compare(password, hash)
  res.json({ ok: true });
});

app.listen(3000);

// Terminal: check dependencies for known vulnerabilities
// npm audit
// npm audit fix

helmet adds headers such as Content-Security-Policy, CORS allows only agyanadda.com, and the sixth login attempt within 15 minutes gets a 429 Too Many Requests response.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which package sets many security headers at once?

Exercise 2 True / False

npm audit checks your dependencies for known vulnerabilities.

Exercise 3 Fill in the Blank

Limit repeated login attempts with express-___-limit

Frequently Asked Questions

It allows requests from any website. That is fine for a public read-only API, but for APIs that use cookies or private data, list only your own frontend domains in the origin option.