AceDevHub
Advanced Node.js Interview QuestionsAdvancedConcept

Node.js · Question 78

What are Node.js security best practices?

Direct answer

Validate all input, parameterize SQL, sanitize paths, use helmet headers, rate-limit auth routes, store secrets in env not code, keep dependencies patched (npm audit), httpOnly cookies for sessions, and enforce auth/entitlements on the server — never trust the client.

Node APIs face OWASP-class risks — injection, broken auth, SSRF, prototype pollution — AceDevHub enforces access in Fastify handlers, not just frontend gates.

Why interviewers ask

RiskMitigation
SQL injectionParameterized queries via pg ($1, $2)
XSSEncode output; CSP headers; sanitize HTML
Path traversalResolve + base check (Q66)
Secret leak.env gitignored; rotate keys
Dependency CVEnpm audit, lockfile, Dependabot
Broken access controlEntitlements check on every gated route
  • Least privilege — DB user read-only where possible; admin routes require role.
  • Error responses — no stack traces or internal paths to clients (Q62).
  • Prototype pollution — avoid merging untrusted objects into {} without validation.
security-handler.mjs
// Parameterized query — never string concat
await pool.query(
  "SELECT * FROM interview_topics WHERE slug = $1",
  [slug]
);

// Server-side entitlement check
if (!await entitlementsService.hasPremium(userId)) {
  throw new AppError("Premium required", 403, "FORBIDDEN");
}