Performance & Security

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

XSS (Cross-Site Scripting)Critical

Attacker injects scripts that execute in victim's browser

Fix: Escape output, use textContent, CSP

CSRF (Cross-Site Request Forgery)High

Forged request from another site using victim's session

Fix: SameSite cookies, CSRF tokens

SQL / Command InjectionCritical

Malicious input alters SQL queries or system commands

Fix: Parameterized queries, allow-lists, no exec()

Sensitive Data ExposureHigh

Secrets, PII, tokens stored or logged insecurely

Fix: Env vars, encryption at rest, HTTPS, no logging secrets

Broken AuthenticationCritical

Weak passwords, missing rate limits, exposed tokens

Fix: bcrypt, rate-limit, HttpOnly cookies, MFA

Insecure DeserializationHigh

Malicious objects snuck through JSON/binary deserialization

Fix: Validate all parsed data, avoid eval() on JSON

ClickjackingMedium

Invisible iframe tricks user into clicking attacker UI

Fix: X-Frame-Options: DENY or CSP frame-ancestors

Open RedirectMedium

Redirect URL from user input leads to phishing site

Fix: Allow-list redirect destinations, validate URL origin

Security Headers Reference

HeaderRecommended ValueProtects Against
Content-Security-Policydefault-src 'self'; script-src 'self' 'nonce-{n}'XSS, code injection
Strict-Transport-Securitymax-age=63072000; includeSubDomains; preloadProtocol downgrade, MITM
X-Frame-OptionsDENYClickjacking
X-Content-Type-OptionsnosniffMIME sniffing
Referrer-Policystrict-origin-when-cross-originData leakage via Referer
Permissions-Policycamera=(), microphone=(), geolocation=()Feature abuse
Cross-Origin-Opener-Policysame-originSpectre attacks, cross-origin access
Cross-Origin-Resource-Policysame-originData leakage cross-origin reads

Common Pitfalls

Using innerHTML with user content — instant XSS if not escaped
Use textContent for plain text, or DOMPurify.sanitize() if you need HTML. Never trust raw user input.
Storing JWT in localStorage — accessible to any JS on the page, stolen by XSS
Use HttpOnly, Secure, SameSite=Strict cookies. Access tokens in memory only; refresh token in cookie.
No rate limiting on auth endpoints — brute-force attacks succeed in minutes
Rate limit login (5 attempts / 15min), add CAPTCHA after failures, lockout with exponential backoff.
Hardcoding secrets in source code — leaked in git history, client bundles
Use environment variables (.env files, secret managers). Never commit .env. Check with git hooks.

Interactive Demo

Code Editor

<input id="name" value='<img src=x onerror="alert(&apos;hacked&apos;)">'>
<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 Function and setTimeout with 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.