← Back to Node.js Course | Chapter 10: Deployment & Best Practices | Lesson 6 of 7

Security best practices

A few habits, like validating input and keeping packages updated, block most common attacks.

In this page:

  1. Security best practices

Security best practices

Validate and sanitize all input, use parameterized queries, hash passwords, set security headers with helmet, use HTTPS, and keep dependencies updated with npm audit.

Limit request sizes, avoid eval, and never expose stack traces. Follow least privilege for tokens and processes.

Note: Run npm audit regularly and update vulnerable packages.

Example: Security best practices

javascript
function escapeHtml(s) {
  return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}
const userInput = '<script>alert("x")</script>';
console.log(escapeHtml(userInput));
const id = "1; DROP TABLE users";
console.log("valid id:", /^\d+$/.test(id));

// Output:
// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;
// valid id: false

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Trusting user input
  2. Building SQL or shell commands from strings
  3. Ignoring npm audit warnings
Chapter Summary
  • Validate all input
  • Use parameterized queries
  • Set security headers with helmet
  • Audit and update dependencies
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.