Frontend Security
Essential frontend security: XSS, CSRF, CSP, authentication patterns, secure storage, and supply chain security.
Frontend security is often overlooked until a breach occurs. Users trust your application with sensitive data; attackers target the browser as the first line of defense. This guide covers the major threats, prevention strategies, and patterns that keep your frontend and users safe.
XSS (Cross-Site Scripting) — Types and Prevention
Reflected, Stored, and DOM-Based XSS
Reflected XSS injects malicious script via URL parameters or form input that the server echoes back without encoding. Stored XSS persists malicious content in a database and renders it to all users who view it. DOM-based XSS occurs entirely in the client—unsafe handling of document.location or innerHTML with user-controlled data. All three allow attackers to steal cookies, session tokens, or perform actions as the user.
Output Encoding and Sanitization
Never render user input as raw HTML. Use text content (React's default, textContent in vanilla JS) or framework-safe interpolation. When you must render HTML (e.g., rich text), use a sanitization library like DOMPurify with a strict allowlist. Encode for the correct context: HTML attributes, JavaScript strings, and URLs each have different encoding rules.
Content Security Policy as Defense in Depth
CSP headers restrict where scripts can load from and block inline script execution. Even if an XSS vulnerability exists, CSP can prevent the payload from running. Use Content-Security-Policy with script-src 'self' and avoid unsafe-inline when possible. Report violations to monitor attempted attacks.
CSRF (Cross-Site Request Forgery) Protection
How CSRF Works
Continue reading Frontend Security
Sign in or create a free account to read the rest of this article and all premium content.
Sign in to continue readingRelated articles
- Frontend ArchitectureFeature Flags and A/B Testing
Ship behind flags, run experiments, and roll out features gradually. How to implement feature flags and A/B testing in frontend applications.
Read article - Frontend ArchitectureInternationalization (i18n)
Supporting multiple languages and regions: locales, formatting, RTL, and translation workflows for frontend applications.
Read article - Frontend ArchitectureFrontend System Design
A structured framework for approaching frontend system design interviews and real-world architecture decisions.
Read article - Frontend ArchitectureMicro-Frontends
When and how to adopt micro-frontends: implementation approaches, trade-offs, and common challenges.
Read article