advanced
CSRF, SSRF, and clickjacking
Use SameSite or CSRF tokens for state changes, validate outbound fetch targets, and block UI framing with frame-ancestors or X-Frame-Options.
CSRF tricks a victim's browser into sending authenticated requests the user did not intend. Defenses: SameSite cookies, CSRF tokens on state-changing forms/APIs, and requiring custom headers for JSON mutations (browsers restrict cross-origin custom headers via preflight).
// Double-submit or synchronizer token pattern
if (req.method !== 'GET' && req.body._csrf !== req.cookies.csrf) {
return res.status(403).json({ error: 'csrf' });
}
SSRF: server fetches attacker-controlled URLs — hitting internal metadata (`169.254.169.254`), Redis, or admin panels. Block private IP ranges, validate URL schemes, use allowlists, and separate fetch proxies with no internal network access.
Clickjacking: embed your site in a transparent iframe to capture clicks. Defend with `Content-Security-Policy: frame-ancestors 'none'` or `X-Frame-Options: DENY`.
On interviews: why CSRF matters less for pure Bearer-token APIs; SSRF in webhooks and PDF generators; when SameSite=Lax is enough.
Common pitfalls: GET endpoints that mutate state; SSRF in image URL importers; framing allowed on sensitive pages.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- SameSite + CSRF token for cookie auth mutations.
- SSRF allowlists and block private IPs on outbound fetch.
- frame-ancestors on authenticated UI routes.
- Audit server-side URL fetch features.