';\nconst safe = sanitizeHTML(userInput);\n// Safe to use in innerHTML\n\n// 2. Content Security Policy (CSP)\n// Add meta tag in HTML:\n// \n\n// 3. Avoid eval() - executes arbitrary code\n// BAD:\n// eval(userInput);\n\n// GOOD:\n// Use JSON.parse() for JSON data\nconst data = JSON.parse(jsonString);\n\n// 4. Validate and sanitize on both client and server\nfunction validateEmail(email) {\n const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;\n return re.test(email);\n}\n\n// 5. Use HTTPS only\n// Enforce with:\n// \n\n// 6. Secure cookies\n// Set flags: HttpOnly, Secure, SameSite\n// document.cookie = \"session=abc; Secure; HttpOnly; SameSite=Strict\";\n\n// 7. Avoid storing sensitive data in localStorage\n// BAD:\n// localStorage.setItem('password', userPassword);\n\n// GOOD:\n// Use httpOnly cookies for session tokens\n\n// 8. CSRF Protection\n// Include CSRF token in forms\nfunction getCSRFToken() {\n return document.querySelector('meta[name=\"csrf-token\"]')\n ?.content;\n}\n\n// Include in fetch requests\nfetch('/api/data', {\n method: 'POST',\n headers: {\n 'X-CSRF-Token': getCSRFToken()\n }\n});\n\n// 9. Rate limiting (server-side)\n// Implement on backend to prevent abuse\n\n// 10. Input validation\nfunction validateAge(age) {\n if (typeof age !== 'number') {\n throw new Error('Age must be a number');\n }\n if (age < 0 || age > 150) {\n throw new Error('Invalid age');\n }\n return age;\n}\n\n// 11. Avoid inline event handlers\n// BAD:\n// \n\n// GOOD:\n// button.addEventListener('click', doSomething);\n\n// 12. Use secure dependencies\n// Regularly update packages\n// npm audit\n// Use tools like Snyk\n\n// 13. Encrypt sensitive data\nasync function encryptData(data, key) {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(data);\n \n const cryptoKey = await crypto.subtle.importKey(\n 'raw', key, 'AES-GCM', false, ['encrypt']\n );\n \n const iv = crypto.getRandomValues(new Uint8Array(12));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n cryptoKey,\n encoded\n );\n \n return { encrypted, iv };\n}\n\n// 14. Secure password handling\n// Never store plain text passwords\n// Use bcrypt or similar on server\n// Hash passwords before sending\n\n// 15. Regular security audits\n// Use tools like OWASP ZAP\n// Conduct code reviews\n// Stay updated on vulnerabilities"
},
{
"@type": "HowToStep",
"name": "Run the Code",
"text": "Click the Run button or press Ctrl+Enter to execute the code."
},
{
"@type": "HowToStep",
"name": "Understand the Output",
"text": "Prevent XSS with sanitization. Use CSP headers. Avoid eval(). Validate input. Use HTTPS. Secure cookies. CSRF tokens. Encrypt sensitive data. Regular audits."
}
]
}
Home / Tutorials / JavaScript / JavaScript Security Best Practices 🔒 JavaScript Security Best Practices JavaScript Intermediate
Protect your applications from common vulnerabilities.
Code Example JavaScript Copy
// 1. XSS Prevention - Sanitize user input
function sanitizeHTML(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
const userInput = '<script>alert("XSS")</script>';
const safe = sanitizeHTML(userInput);
// Safe to use in innerHTML
// 2. Content Security Policy (CSP)
// Add meta tag in HTML:
// <meta http-equiv="Content-Security-Policy"
// content="default-src 'self'; script-src 'self'">
// 3. Avoid eval() - executes arbitrary code
// BAD:
// eval(userInput);
// GOOD:
// Use JSON.parse() for JSON data
const data = JSON.parse(jsonString);
// 4. Validate and sanitize on both client and server
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
// 5. Use HTTPS only
// Enforce with:
// <meta http-equiv="Content-Security-Policy"
// content="upgrade-insecure-requests">
// 6. Secure cookies
// Set flags: HttpOnly, Secure, SameSite
// document.cookie = "session=abc; Secure; HttpOnly; SameSite=Strict";
// 7. Avoid storing sensitive data in localStorage
// BAD:
// localStorage.setItem('password', userPassword);
// GOOD:
// Use httpOnly cookies for session tokens
// 8. CSRF Protection
// Include CSRF token in forms
function getCSRFToken() {
return document.querySelector('meta[name="csrf-token"]')
?.content;
}
// Include in fetch requests
fetch('/api/data', {
method: 'POST',
headers: {
'X-CSRF-Token': getCSRFToken()
}
});
// 9. Rate limiting (server-side)
// Implement on backend to prevent abuse
// 10. Input validation
function validateAge(age) {
if (typeof age !== 'number') {
throw new Error('Age must be a number');
}
if (age < 0 || age > 150) {
throw new Error('Invalid age');
}
return age;
}
// 11. Avoid inline event handlers
// BAD:
// <button onclick="doSomething()">
// GOOD:
// button.addEventListener('click', doSomething);
// 12. Use secure dependencies
// Regularly update packages
// npm audit
// Use tools like Snyk
// 13. Encrypt sensitive data
async function encryptData(data, key) {
const encoder = new TextEncoder();
const encoded = encoder.encode(data);
const cryptoKey = await crypto.subtle.importKey(
'raw', key, 'AES-GCM', false, ['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
cryptoKey,
encoded
);
return { encrypted, iv };
}
// 14. Secure password handling
// Never store plain text passwords
// Use bcrypt or similar on server
// Hash passwords before sending
// 15. Regular security audits
// Use tools like OWASP ZAP
// Conduct code reviews
// Stay updated on vulnerabilitiesExplanation Prevent XSS with sanitization. Use CSP headers. Avoid eval(). Validate input. Use HTTPS. Secure cookies. CSRF tokens. Encrypt sensitive data. Regular audits.
Try This Code in the Editor
Free online code editor that runs entirely in your browser. Python, JavaScript, HTML/CSS, and SQL — no server, no signup, no limits.
© 2026 CompileZ. All rights reserved. Free online code editor.
Privacy First 100% In-Browser Free Forever