Top 3 Web Threats
Most real-world web compromises trace back to a small set of vulnerability classes. Understanding these three covers the majority of attack surface in modern web applications.
Cross-Site Scripting (XSS)
XSS occurs when user-controlled data is rendered as HTML without sanitization. The injected script runs in the victim's browser with full access to cookies, localStorage, and the DOM.
// Vulnerable: directly injecting user input renders scripts
element.innerHTML = userInput;
// Safe: use textContent — never parsed as HTML
element.textContent = userInput;
// Safe: sanitize when HTML formatting is required
import DOMPurify from "dompurify";
element.innerHTML = DOMPurify.sanitize(userInput);dangerouslySetInnerHTML bypasses all escaping. Treat it exactly like raw innerHTML and always sanitize before use.CSRF Attacks
CSRF exploits the browser's automatic cookie-sending behavior. A logged-in user visiting a malicious page can have requests silently submitted to your server — authenticated and indistinguishable from legitimate ones.
// Server: generate a token and store it in the session
const token = crypto.randomBytes(32).toString("hex");
req.session.csrfToken = token;
// HTML: embed token in every state-changing form
<input type="hidden" name="csrf_token" value={token} />
// Server: validate on every mutating request
if (req.body.csrf_token !== req.session.csrfToken) {
return res.status(403).json({ error: "Invalid CSRF token" });
}SameSite=Strict or SameSite=Lax on session cookies blocks cross-site requests at the browser level — no token logic required. This is the modern first-line defense against CSRF.Content Security Policy (CSP)
CSP is an HTTP response header that tells browsers which sources are trusted for scripts, styles, and other resources. A well-tuned CSP is the strongest available defense against XSS — even if injection happens, the script cannot execute.
# Nginx — enforce CSP header
add_header Content-Security-Policy "
default-src 'self';
script-src 'self' 'nonce-{RANDOM}';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
" always;
# Next.js — next.config.ts headers()
{
key: "Content-Security-Policy",
value: "default-src 'self'; script-src 'self' 'nonce-{RANDOM}';",
}Content-Security-Policy-Report-Only first to collect violation reports without blocking anything. Move to the enforcing header only after confirming no legitimate resources are affected.