Basic Docs
securityweb

Web Security Essentials

Protect your web app from XSS, CSRF, and injection attacks.

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.

XSS
Attacker injects malicious scripts into pages viewed by other users, stealing cookies, sessions, or credentials.
CSRF
Tricks an authenticated user into unknowingly sending a state-changing request to your server from a malicious site.
Injection
Untrusted input is executed as code — SQL queries, shell commands, or template expressions evaluated server-side.
Injection
OWASP #1 Threat
Top-ranked web security risk
67%
XSS Exposure
Of tested sites contain XSS flaws
SameSite
CSRF Defense
Cookie-level protection
CSP
XSS Mitigation
Strongest available header defense

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.

Attacker
Inject Script
User Browser
Steal Data
XSS — Vulnerable vs Safe
// 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);
XSS Attack Flow
1
Attacker
Crafts malicious input payload
2
Inject
Submits script via form or URL parameter
3
Server Stores
Input saved without sanitization
4
User Loads
Victim visits the infected page
5
Script Executes
Runs in victim's browser context
6
Data Stolen
Cookies and session tokens exfiltrated
!React Note
React escapes JSX output by default, making most XSS impossible. However, 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.

User logged in
Visits evil site
Evil site sends request
Server accepts
CSRF Token Pattern
// 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 Cookies
Setting 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.

CSP Header Configuration
# 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}';",
}
iStart With Report-Only
Deploy 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.

Security Checklist

1
Validate All Input Server-Side
Never trust client-side validation alone. Every piece of user input must be validated and sanitized on the server before processing or storage.
2
Use Parameterized Queries
Never concatenate user input into raw SQL strings. Use prepared statements or an ORM — this eliminates SQL injection at the source.
3
Set Secure Cookie Flags
All session cookies must have HttpOnly (blocks JS access), Secure (HTTPS only), and SameSite=Lax or Strict to prevent session hijacking and CSRF.
4
Enforce HTTPS with HSTS
Redirect all HTTP to HTTPS and add Strict-Transport-Security headers so browsers remember to always use secure connections for your domain.
5
Keep Dependencies Updated
Run npm audit or enable Dependabot on every repository. The majority of production breaches exploit known CVEs in outdated packages.
Built: 4/8/2026, 12:01:11 PM