Skip to content

Security

Security is critical for production applications. JavaScript has specific vulnerabilities to be aware of, especially in client-side code.

// ❌ Vulnerable — innerHTML with user input
element.innerHTML = userInput;
// ✅ Safe — textContent
element.textContent = userInput;
// ✅ Safe — sanitize before using innerHTML
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
// Use SameSite cookies
document.cookie = 'session=abc123; SameSite=Strict; Secure';
// Include CSRF tokens in requests
fetch('/api/data', {
headers: {
'CSRF-Token': csrfToken
}
});
  • ✅ Use HTTPS everywhere
  • ✅ Sanitize user input (never trust it)
  • ✅ Implement Content Security Policy (CSP)
  • ✅ Keep dependencies updated (npm audit)
  • ✅ Use Helmet for Express.js headers
  • ✅ Use Strict mode for CSP
  • ✅ Limit data exposure in API responses
  • XSS: sanitize user input, use textContent
  • CSRF: use SameSite cookies, CSRF tokens
  • CSP: restrict which scripts can execute
  • npm audit: check for vulnerable dependencies
  • Security is everyone’s responsibility