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
| Risk | Mitigation |
|---|---|
| SQL injection | Parameterized queries via pg ($1, $2) |
| XSS | Encode output; CSP headers; sanitize HTML |
| Path traversal | Resolve + base check (Q66) |
| Secret leak | .env gitignored; rotate keys |
| Dependency CVE | npm audit, lockfile, Dependabot |
| Broken access control | Entitlements 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");
}