Security
Security
Section titled “Security”Introduction
Section titled “Introduction”Security is critical for production applications. JavaScript has specific vulnerabilities to be aware of, especially in client-side code.
XSS (Cross-Site Scripting)
Section titled “XSS (Cross-Site Scripting)”// ❌ Vulnerable — innerHTML with user inputelement.innerHTML = userInput;
// ✅ Safe — textContentelement.textContent = userInput;
// ✅ Safe — sanitize before using innerHTMLimport DOMPurify from 'dompurify';element.innerHTML = DOMPurify.sanitize(userInput);CSRF Prevention
Section titled “CSRF Prevention”// Use SameSite cookiesdocument.cookie = 'session=abc123; SameSite=Strict; Secure';
// Include CSRF tokens in requestsfetch('/api/data', { headers: { 'CSRF-Token': csrfToken }});Security Checklist
Section titled “Security Checklist”- ✅ Use HTTPS everywhere
- ✅ Sanitize user input (never trust it)
- ✅ Implement Content Security Policy (CSP)
- ✅ Keep dependencies updated (npm audit)
- ✅ Use
Helmetfor Express.js headers - ✅ Use
Strictmode for CSP - ✅ Limit data exposure in API responses
Summary
Section titled “Summary”- 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