๐ JavaScript Security Basics
Web security is critical when writing JavaScript, especially when working with user inputs, APIs, and the DOM. Below are some of the core JavaScript security practices every developer should know.
๐งผ 1. Input Sanitization
Always sanitize and validate user inputs to prevent malicious code from being injected or misused.
const sanitize = (input) => {
const div = document.createElement("div");
div.textContent = input;
return div.innerHTML;
};
๐ซ 2. Avoid eval()
and new Function()
Using eval()
opens your application to code injection attacks. Always avoid dynamic code execution unless absolutely necessary.
โ ๏ธ 3. Cross-Site Scripting (XSS) Protection
XSS allows attackers to inject malicious scripts into webpages. Never directly insert user input into the DOM without sanitizing.
Use textContent instead of innerHTML when outputting untrusted data.
๐ 4. Use HTTPS & Secure APIs
Always use HTTPS to encrypt data in transit. Never send sensitive information over HTTP. Ensure your backend APIs support and enforce HTTPS.
๐ 5. Cross-Origin Resource Sharing (CORS)
CORS policies define which domains can communicate with your server. Set appropriate headers on your API to avoid exposing data to unintended sources.
// Example: Express.js
res.setHeader("Access-Control-Allow-Origin", "https://yourdomain.com");
๐ 6. Content Security Policy (CSP)
A CSP header restricts which scripts and resources are allowed to run on your page, preventing XSS and data injection attacks.
// Example HTTP Header
Content-Security-Policy: default-src 'self'; script-src 'self';
๐ 7. Avoid Hardcoding Secrets
Never expose API keys, tokens, or passwords in frontend JavaScript. Use environment variables on the server side to protect credentials.
npm audit
.