Back
๐Ÿ—๏ธ

Cheatsheet โ€” System Design

Protocols ยท Machine Coding ยท Performance ยท Storage ยท Security

๐Ÿ”’ 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)