JavaScript
2 min read
Updated 4 Aug 2026
Part 24 — Security
Revision notes.
| Threat | What it is | Defence |
|---|---|---|
| XSS | attacker-injected script runs in your page | escape output, textContent not innerHTML, sanitize (DOMPurify), CSP |
| CSRF | forged request using the victim's cookies | CSRF tokens, SameSite cookies, check origin |
| CORS | browser blocks cross-origin reads by default | server sets Access-Control-Allow-*; don't disable checks blindly |
| CSP | Content-Security-Policy header restricting sources | default-src 'self'; blocks inline scripts/injections |
| Injection | untrusted data in queries/HTML | parameterize, validate, escape |
| Insecure storage | secrets/tokens in localStorage |
prefer httpOnly cookies for auth tokens |
// ❌ XSS — never do this with user input
el.innerHTML = userInput;
// ✅ safe
el.textContent = userInput;
el.append(document.createTextNode(userInput));
Cookies:
Set-Cookie: token=...; HttpOnly; Secure; SameSite=Strict; Path=/
HttpOnly→ JS can't read it (mitigates XSS token theft).Secure→ HTTPS only.SameSite→ CSRF mitigation.
JWT basics: a signed token header.payload.signature. The signature proves integrity; the payload is base64, not encrypted — never put secrets in it. Verify signature server-side; keep expiry short; store carefully (httpOnly cookie preferred over localStorage).
Secure coding: validate all input, never trust the client, use parameterized queries, keep dependencies patched (npm audit), avoid eval/new Function on untrusted input, apply least privilege, don't leak stack traces to users.
Interview questions (Part 24):
- What is XSS and three ways to prevent it? Where does CSP fit?
- How does
SameSitehelp against CSRF? - Why is it risky to store JWTs in
localStorage?