๐ Frontend Security Essentials
XSS โ Cross-Site Scripting
Attacker injects malicious scripts that run in the victim's browser.
- โ Reflected XSS โ script in URL parameter, reflected in response
- โ Stored XSS โ script stored in DB, served to all users
- โ DOM XSS โ script injected via client-side JS (innerHTML, eval)
Prevention:
- โNever use innerHTML/dangerouslySetInnerHTML with untrusted data
- โSanitize HTML: DOMPurify before rendering user content
- โContent Security Policy (CSP) header โ whitelist allowed sources
- โReact auto-escapes JSX โ stay in JSX, do not bypass it
CSRF โ Cross-Site Request Forgery
Attacker tricks the user's browser into sending an authenticated request to your server.
- โSameSite=Strict/Lax cookie attribute (modern fix)
- โCSRF token โ server generates, client sends in header
- โCheck Origin/Referer headers on server
- โDo not use GET for state-changing operations
// Send CSRF token with requests axios.defaults.headers.common["X-CSRF-Token"] = getCsrfToken();
Content Security Policy (CSP)
<!-- Via HTTP header (preferred) or meta tag --> Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://cdn.example.com; connect-src 'self' https://api.example.com; frame-ancestors 'none';
Nonce-based CSP is best โ no unsafe-inline, each inline script gets a unique nonce.
Auth Patterns
JWT in HttpOnly cookie Most secure โ JS can't read it, protected from XSS
JWT in localStorage Convenient but XSS can steal it โ
Session cookie Server-side session, stateful. SameSite + HttpOnly.
OAuth 2.0 / PKCE For third-party login. Use PKCE flow for SPAs (no client secret)
Refresh tokens Short-lived access token + long-lived refresh token (rotation)
Other Security Headers
X-Content-Type-Options: nosniff Prevent MIME sniffing attacks
X-Frame-Options: DENY Prevent clickjacking (now: frame-ancestors 'none' in CSP)
Strict-Transport-Security Force HTTPS (HSTS)
Referrer-Policy: no-referrer Do not send referrer URL to other origins
Permissions-Policy Restrict browser features (camera, location, mic)
Input Validation & Other Tips
- โ Validate on client (UX) + server (security) โ never just client
- โ Avoid eval(), new Function(), setTimeout(string)
- โ Use textContent instead of innerHTML for plain text
- โ Subresource Integrity (SRI) for 3rd party scripts/styles
- โ Keep dependencies updated โ audit with npm audit
- โ Don't expose API keys in client-side JS (use env vars + server proxy)