Web Security
Security is not optional. Learn how to prevent XSS, CSRF, injection attacks, and sensitive data exposure. Understand Content Security Policy, security headers, safe token storage, and input validation to build secure applications.
How do I write secure JavaScript?
Never trust user input. Prevent XSS by using textContent instead of innerHTML (or sanitising with DOMPurify), keep secrets and API keys out of front-end code, validate everything on the server, and use HTTP-only cookies rather than localStorage for session tokens. Add a Content-Security-Policy, and keep dependencies updated (npm audit).
el.textContent = comment.text; // safe
el.innerHTML = DOMPurify.sanitize(comment.html); // only if HTML is required
// Never: eval(userInput), new Function(userInput)OWASP Top Threats
Attacker injects scripts that execute in victim's browser
Fix: Escape output, use textContent, CSP
Forged request from another site using victim's session
Fix: SameSite cookies, CSRF tokens
Malicious input alters SQL queries or system commands
Fix: Parameterized queries, allow-lists, no exec()
Secrets, PII, tokens stored or logged insecurely
Fix: Env vars, encryption at rest, HTTPS, no logging secrets
Weak passwords, missing rate limits, exposed tokens
Fix: bcrypt, rate-limit, HttpOnly cookies, MFA
Malicious objects snuck through JSON/binary deserialization
Fix: Validate all parsed data, avoid eval() on JSON
Invisible iframe tricks user into clicking attacker UI
Fix: X-Frame-Options: DENY or CSP frame-ancestors
Redirect URL from user input leads to phishing site
Fix: Allow-list redirect destinations, validate URL origin
Security Headers Reference
| Header | Recommended Value | Protects Against |
|---|---|---|
| Content-Security-Policy | default-src 'self'; script-src 'self' 'nonce-{n}' | XSS, code injection |
| Strict-Transport-Security | max-age=63072000; includeSubDomains; preload | Protocol downgrade, MITM |
| X-Frame-Options | DENY | Clickjacking |
| X-Content-Type-Options | nosniff | MIME sniffing |
| Referrer-Policy | strict-origin-when-cross-origin | Data leakage via Referer |
| Permissions-Policy | camera=(), microphone=(), geolocation=() | Feature abuse |
| Cross-Origin-Opener-Policy | same-origin | Spectre attacks, cross-origin access |
| Cross-Origin-Resource-Policy | same-origin | Data leakage cross-origin reads |
Common Pitfalls
Interactive Demo
Code Editor
<input id="name" value='<img src=x onerror="alert('hacked')">'>
<button id="unsafe">innerHTML (unsafe)</button>
<button id="safe">textContent (safe)</button>
<div id="out"></div>Preview
JavaScript Security: summary
Key points
- Anything in client JavaScript is public, including environment variables bundled into it.
- CSRF: use SameSite cookies and CSRF tokens for state-changing requests.
- Avoid
eval,new FunctionandsetTimeoutwith string arguments. - Pin and review dependencies; supply-chain attacks target npm packages.
Frequently asked questions
›Can I hide an API key in front-end JavaScript?
No. Anyone can read it in DevTools. Call the third-party API from your server and keep the key there.