# Frontend Security: XSS, CSRF, CSP, and Modern Defenses

Source: https://www.techinterview.org/post/3233475082/frontend-security-xss-csrf-csp/
Updated: 2026-05-05 · techinterview.org

Frontend security is increasingly tested in senior interviews — not because every engineer should be a security specialist but because the consequences of getting basic patterns wrong are catastrophic. XSS, CSRF, and SSRF are the OWASP top three; understanding the defenses is professional baseline.

## Cross-Site Scripting (XSS)

The attacker injects script that runs in the victim's browser. Three types:

- **Stored XSS:** attacker script saved on server (e.g., in a comment), runs for every viewer

- **Reflected XSS:** attacker tricks user into clicking a URL that includes script

- **DOM-based XSS:** attacker exploits client-side JS that uses untrusted data unsafely

### Defenses

- Always escape output. React, Vue, and modern frameworks do this by default — bypass only with explicit raw-HTML props

- Sanitize HTML input with DOMPurify if you must accept HTML

- Set Content Security Policy headers

- Use Trusted Types API (Chromium-only as of 2026) to enforce safe sinks at runtime

## Content Security Policy (CSP)

HTTP header that whitelists allowed sources for scripts, styles, images, etc.


```
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'
```


A strict CSP is the single most effective XSS mitigation. Even if attacker injects script, CSP blocks execution.

Common gotcha: `unsafe-inline` defeats most of the protection. Use nonces or hashes instead.

## Cross-Site Request Forgery (CSRF)

Attacker tricks the user's browser into making a request to your site that the user did not intend. Browser sends cookies; the request looks authenticated.

### Defenses

- **SameSite cookies:** set `SameSite=Lax` or `Strict` on auth cookies. Browser refuses to send them on cross-site requests.

- **CSRF tokens:** server generates a token, embeds in the form, validates on submit. Attacker cannot read the token from another origin.

- **Custom request headers:** require an X-Custom-Header on state-changing requests; CORS prevents arbitrary origins from setting it.

Modern web apps using SPA + JSON APIs typically rely on SameSite + token in header (not in cookie).

## SameSite cookies

Three values:

- **Strict:** cookie sent only on same-site requests. Most secure; can disrupt legitimate flows like reflecting back from a payment processor.

- **Lax (default in 2026):** cookie sent on same-site + top-level GET navigations from other sites. Reasonable balance.

- **None:** cookie sent on all requests. Requires Secure flag. Use only when needed for cross-site embedded use cases.

## Subresource Integrity (SRI)

For third-party scripts loaded from CDN, include a hash:


```
<script src="https://cdn.example.com/lib.js" integrity="sha384-abc..." crossorigin="anonymous">
```


Browser refuses to execute the script if the hash does not match. Defeats CDN tampering.

## Clickjacking

Attacker iframes your site, overlays invisible UI, tricks user into clicking on hidden buttons.

Defenses:

- `X-Frame-Options: DENY` or `SAMEORIGIN` header

- `Content-Security-Policy: frame-ancestors 'self'`

## HTTPS and HSTS

HTTPS everywhere is table stakes. Add HSTS (HTTP Strict Transport Security) header to force browsers to use HTTPS even for typed-in URLs.

Submit your site to HSTS preload list for browser-baked enforcement.

## Secrets in the frontend

Never put secrets in frontend code:

- API keys with privileged access

- Database credentials

- Internal admin URLs

Anything in JS source is public. Use a backend proxy for privileged operations.

## Third-party scripts

Every third-party script (analytics, ads, fonts) is a potential XSS source. Mitigations:

- SRI hashes for static URLs

- Sandboxed iframes for ad networks

- CSP whitelist of allowed origins

- Audit periodically

## Common interview probes

- "How does XSS happen and how do you prevent it?"

- "Walk through CSRF and three defenses"

- "What is CSP and what is unsafe-inline?"

- "How do SameSite cookies prevent CSRF?"

## Frequently Asked Questions

### Does using React eliminate XSS risk?

Mostly. React escapes by default. The risk lives in raw-HTML props, `innerHTML`, and unsafe URL handling (e.g., `href={userInput}` without protocol check).

### Should I use httpOnly cookies for auth?

Yes for tokens stored in cookies — prevents JS access (mitigates XSS-based theft). Use Secure and SameSite as well.

### Are JWTs in localStorage safer or less safe?

Less safe than httpOnly cookies. localStorage is JS-readable, so an XSS allows token theft. Cookies with httpOnly cannot be stolen from JS.
