A practical guide to securing frontend applications against the most common web vulnerabilities. Every React/Next.js developer should know how XSS works, why CSRF tokens exist, what CSP directives mean, and how to build a defense-in-depth posture without slowing down development.
FrontendX EngineeringSystem Design Series #10
What Are We Building?
Web security is not a feature you bolt on at the end. It is an architectural property that must be designed into every layer of your application — from the HTTP headers your server sends to the way your React components render user input. One mistake — a missing SameSite cookie attribute, an innerHTML assignment without sanitization, a CORS policy that is too permissive — and your application is compromised.
In this article I walk through the architecture of a security-hardened frontend application. Not a theoretical overview of OWASP Top 10 — I mean actual code: CSP headers you can copy into your Next.js config, CSRF token generation you can use in your Express routes, a bcrypt hashing utility for your database layer, and a rate limiter that protects your API endpoints.
Here is the architecture I settled on — a defense-in-depth stack with five layers, each catching what the layer above might miss. No single mitigation is sufficient; security is a property of the system, not a single feature.
Figure 1 — Defense-in-depth layers. Security is not a single feature; it is a stack of mitigations at every level from the network to the client.
The core idea: every layer has a job. The network layer blocks DDoS and malicious IPs. Transport ensures encryption. Application enforces authentication and CSRF protection. Content prevents XSS. The client enforces Same-Origin Policy. An attacker must breach every layer to cause real damage.
1 · Requirements & Scoping
Before writing a single line of security code, I ask: what are we protecting, and from whom? The threat model determines the defense budget. A personal blog needs different controls than a banking dashboard.
Functional requirements
XSS prevention: User-generated content must never execute scripts. React's default JSX escaping covers most cases, but dangerouslySetInnerHTML requires explicit sanitization. Trusted Types provide a browser-enforced safety net.
CSRF protection: Mutating requests (POST, PUT, DELETE) must include a server-verified token. Combined with SameSite=Lax cookies, this prevents cross-site request forgery.
HTTPS enforcement: All traffic must use TLS 1.3. HTTP requests must redirect or be rejected. HSTS headers tell browsers to always use HTTPS for this origin.
Input validation and sanitization: Every user input must be validated on the server (not just the client). SQL injection is prevented by parameterized queries. HTML injection is prevented by server-side sanitization.
Secure session management: Session tokens must be HttpOnly, Secure, SameSite. Sessions must expire after inactivity. Password storage must use bcrypt or Argon2.
Rate limiting: API endpoints must limit requests per user/IP to prevent brute force and abuse.
Non-functional requirements
Defense in depth: No single point of failure. If one defense is bypassed, the next must catch the attack.
Minimal performance overhead: Security controls must not add more than 5ms to the p95 response time. Bcrypt hashing (cost=12) is acceptable for login but not for every request.
Fail securely: If a security component fails (misconfigured CSP, expired TLS certificate), the system must default to a locked-down state, not an open one.
Auditability: Security-relevant events (failed logins, CSRF validation failures, CSP violations) must be logged with sufficient context for forensic analysis.
Composability: Security controls should be implemented as middleware or utility functions, not scattered across every route handler. A single configuration file should define the security posture.
Tip
I deliberately scoped out quantum-safe cryptography and hardware security modules. Those are relevant for defense systems and cryptocurrency exchanges, but the OWASP Top 10 — XSS, CSRF, injection, broken authentication — accounts for 80% of web breaches. Master these first.
2 · Architecture & High-Level Design
The central architectural question for web security is: where do the defenses live? Client-side-only security is theater — a determined attacker bypasses your React validation by sending raw HTTP requests. Server-side-only security misses browser-level protections like CSP and Trusted Types. The answer is both: layered defense with each layer operating at its own level of the stack.
I organize the security architecture into four logical domains:
Domain 1: Transport Security (middleware layer)
HTTPS redirect, HSTS headers, and TLS configuration. This is the easiest domain to get right because it is purely configuration — no application logic involved. I use Helmet (or a custom middleware) to set Strict-Transport-Security, X-Content-Type-Options, and Referrer-Policy on every response.
Domain 2: Content Security (CSP + SRI)
Content Security Policy is a browser-enforced allowlist. It tells the browser which origins are trusted for scripts, styles, fonts, images, and connections. Combined with Subresource Integrity (SRI) hashes for CDN assets, this domain ensures that even if an attacker injects a script tag, the browser refuses to execute it. I cover the specific directives below in the Deep Dive.
This is where most security code lives: session management, CSRF tokens, input validation, rate limiting, and audit logging. These are implemented as middleware or utility functions that wrap route handlers.
The browser enforces Same-Origin Policy, Trusted Types, and secure cookie attributes. React's JSX escaping is the first line of defense against XSS, but I also use Trusted Types to prevent DOM-based XSS via innerHTML sinks.
Key Insight
I rejected the "security is the backend's job" mindset early. Modern frontend security is a shared responsibility. The backend enforces access control and validates input. The frontend enforces CSP, Trusted Types, and secure cookie storage. Both are necessary; neither is sufficient alone.
3 · Data Model & State Shape
Security data entities are different from your domain entities. They represent trust boundaries, not business objects. Here are the key types I define in a security-hardened application.
Session hijacking is when an attacker steals a session cookie and replays it from a different device. By storing the ipAddress and userAgent that created the session, I can detect when a session is suddenly used from a different environment. This is not a hard block — IP addresses change legitimately (mobile users switching from WiFi to cellular) — but it triggers an additional verification step (MFA challenge).
Rate limiter data model
rate-limiter.tstypescript
// Token bucket rate limiter — in-memoryinterface Bucket { tokens: number; lastRefill: number;}export class TokenBucket { private buckets = new Map<string, Bucket>(); constructor( private maxTokens: number = 100, private refillRate: number = 10, // tokens per second private refillInterval: number = 1000, // ms ) {} allow(key: string): boolean { const now = Date.now(); let bucket = this.buckets.get(key); if (!bucket) { bucket = { tokens: this.maxTokens, lastRefill: now }; this.buckets.set(key, bucket); } // Refill tokens const elapsed = now - bucket.lastRefill; const refillTokens = Math.floor( (elapsed / this.refillInterval) * this.refillRate, ); if (refillTokens > 0) { bucket.tokens = Math.min(this.maxTokens, bucket.tokens + refillTokens); bucket.lastRefill = now; } // Consume a token if (bucket.tokens > 0) { bucket.tokens--; return true; } return false; } // Clean up stale buckets periodically cleanup(maxAge: number = 3600000) { const cutoff = Date.now() - maxAge; for (const [key, bucket] of this.buckets) { if (bucket.lastRefill < cutoff) this.buckets.delete(key); } }}
The token bucket algorithm is my preferred rate limiter. It allows short bursts (up to maxTokens) while enforcing a sustained rate (refillRate tokens per second). This is more forgiving than a fixed window counter, which can block legitimate users who happen to send requests near the window boundary.
For distributed rate limiting, replace the in-memory Map with Redis. The interface stays the same — the implementation swaps the storage backend.
Password storage
password.tstypescript
// Password hashing with bcrypt — never store plaintextimport bcrypt from "bcrypt";const SALT_ROUNDS = 12; // ~250ms per hash on modern hardwareexport async function hashPassword(password: string): Promise<string> { return bcrypt.hash(password, SALT_ROUNDS);}export async function verifyPassword( password: string, hash: string,): Promise<boolean> { return bcrypt.compare(password, hash);}// Why bcrypt and not SHA-256?// bcrypt is deliberately slow (adaptive cost factor).// SHA-256 is designed to be fast — an attacker can try billions of// guesses per second with GPU hardware. bcrypt at cost 12 limits// brute-force to ~4 guesses per second per GPU core.
Note
I use bcrypt with cost factor 12. Argon2id is technically more secure (it won the PHC), but bcrypt has wider library support and is less sensitive to configuration mistakes. For most applications, bcrypt at cost 12 provides adequate protection against GPU-accelerated brute force. If you are building a high-security system, use Argon2id.
4 · Interface Definition (API)
Security APIs are the contracts between the client and the server's enforcement layer. These are not your domain API routes — they are the headers, tokens, and middleware that wrap those routes.
Server-side: security middleware
security-middleware.tstypescript
// Next.js middleware — set security headers on every response// Equivalent to Helmet for Express, but framework-agnosticimport { NextResponse } from "next/server";import type { NextRequest } from "next/server";export function middleware(req: NextRequest) { const res = NextResponse.next(); // HSTS — enforce HTTPS res.headers.set( "Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload", ); // Prevent MIME sniffing res.headers.set("X-Content-Type-Options", "nosniff"); // Referrer policy — only send origin for cross-origin res.headers.set("Referrer-Policy", "strict-origin-when-cross-origin"); // Disable FLoC (federated learning of cohorts) res.headers.set("Permissions-Policy", "interest-cohort=()"); // Prevent clickjacking (redundant with CSP frame-ancestors) res.headers.set("X-Frame-Options", "DENY"); // XSS filter (legacy, most browsers removed support) res.headers.set("X-XSS-Protection", "0"); // Content-Type header safety res.headers.set("X-Download-Options", "noopen"); return res;}
CORS contract
cors.tstypescript
// Express CORS middleware with explicit origin whitelistconst ALLOWED_ORIGINS = [ "https://frontendx.dev", "https://www.frontendx.dev", "https://staging.frontendx.dev",] as const;export function corsMiddleware(req: Request, res: Response, next: () => void) { const origin = req.headers.get("origin"); if (!origin || ALLOWED_ORIGINS.includes(origin as typeof ALLOWED_ORIGINS[number])) { res.headers.set("Access-Control-Allow-Origin", origin ?? "*"); res.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); res.headers.set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token"); res.headers.set("Access-Control-Allow-Credentials", "true"); res.headers.set("Access-Control-Max-Age", "86400"); } // Handle preflight if (req.method === "OPTIONS") { return new Response(null, { status: 204, headers: res.headers }); } next();}
I explicitly whitelist origins. Using Access-Control-Allow-Origin: * with credentials is invalid per the spec and dangerous without it. The preflight handler (OPTIONS) must respond with 204 and the correct CORS headers before the actual request is sent.
CSRF token contract
csrf.tstypescript
// Server: generate and validate CSRF tokensimport { createHash, randomBytes } from "node:crypto";const CSRF_SECRET = process.env.CSRF_SECRET!;export function generateCsrfToken(sessionId: string): string { const payload = `${sessionId}:${CSRF_SECRET}`; return createHash("sha256").update(payload).digest("hex");}export function validateCsrfToken( token: string, sessionId: string,): boolean { const expected = generateCsrfToken(sessionId); // Constant-time comparison to prevent timing attacks if (token.length !== expected.length) return false; return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(expected));}// Client: attach CSRF token to mutating requestsasync function submitForm(data: FormData, csrfToken: string) { const res = await fetch("/api/transfer", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrfToken, }, body: JSON.stringify(data), }); return res.json();}
The CSRF token is a server-derived HMAC of the session ID. The client includes it in the X-CSRF-Token header on mutating requests. The server validates it with a constant-time comparison. I use crypto.timingSafeEqual to prevent timing attacks — a naive string comparison reveals one byte at a time.
Client-side: secure cookie contract
cookies.tstypescript
// Setting secure cookies — server sidefunction setSessionCookie(res: Response, sessionId: string) { res.headers.set( "Set-Cookie", `session_id=${sessionId}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=86400`, );}// Cookie attribute reference:// HttpOnly → not accessible via document.cookie (prevents XSS cookie theft)// Secure → only sent over HTTPS// SameSite=Lax → not sent on cross-site POST (prevents CSRF)// SameSite=Strict → never sent cross-site (most secure, breaks some flows)// Path=/ → cookie scope limited to this path// Max-Age=86400 → 24-hour expiry// Domain=example.com → restrict to specific domain (omit for subdomain isolation)
Every cookie attribute has a specific threat it mitigates. HttpOnly blocks document.cookie access — an XSS attacker can still run scripts, but they cannot read the session token. Secure prevents accidental transmission over HTTP. SameSite=Lax blocks CSRF for mutating methods while preserving top-level navigation.
Warning
The X-CSRF-Token header must NOT be readable via JavaScript. Store it in a meta tag rendered by the server, or fetch it from a dedicated /api/csrf-token endpoint that is itself protected by SameSite cookies. Never put the CSRF secret in a JavaScript variable that an XSS attacker could read.
5 · Component Deep Dive
Let's examine the five most critical security subsystems in detail. Each one has subtleties that are easy to miss.
XSS — the most common critical vulnerability
Cross-Site Scripting (XSS) occurs when an attacker injects malicious scripts into a page that other users view. There are three variants: reflected (injected via URL), stored (persisted in a database), and DOM-based (injected via client-side sinks like innerHTML).
React's JSX escaping is your first defense. When you write {text}, React calls textContent internally, which treats the value as text, not HTML. The dangerouslySetInnerHTML prop bypasses this protection — the name is deliberately alarming. If you must use it, sanitize the input first:
DOMPurify is the industry standard for HTML sanitization. It removes event handlers, javascript: URLs, and other XSS vectors while preserving safe HTML elements. I explicitly whitelist allowed tags and attributes — the deny-list approach (blocking specific dangerous patterns) invariably misses something.
Figure 2 — Reflected XSS attack flow and the four-layer mitigation stack. CSP blocks inline scripts, output encoding neutralizes injected markup, Trusted Types prevents DOM-based XSS, and SRI verifies third-party assets.
Content Security Policy — the fine print
CSP is a browser security mechanism that specifies which resources the page is allowed to load. The policy is delivered as an HTTP header or meta tag. Here is my recommended starting policy for a Next.js application:
The key directives: default-src 'self' is the fallback for all resource types. script-src controls which scripts can execute — omit 'unsafe-inline' if possible, but Next.js requires it for its inline bootstrap scripts. frame-ancestors 'none' prevents clickjacking (modern replacement for X-Frame-Options). form-action 'self' prevents attacker-controlled forms from submitting to your endpoints.
Warning
CSP is difficult to deploy incrementally. Start in report-only mode: Content-Security-Policy-Report-Only. The browser reports violations via the report-uri or report-to directive without blocking anything. Monitor the reports, fix the violations, then switch to enforce mode. I have seen teams break their entire application on the first CSP deployment.
Trusted Types — browser-enforced DOM XSS prevention
trusted-types.tstypescript
// Trusted Types policy — block DOM XSS at the browser level// Install via CSP header or meta tag:// Content-Security-Policy: require-trusted-types-for 'script'// Create a policy for safe HTML insertionconst sanitizePolicy = trustedTypes.createPolicy("sanitize", { createHTML: (input: string) => { // Only allow known safe patterns const safe = input .replace(/<script[^>]*>.*<\/script>/gi, "") .replace(/on\w+\s*=\s*["'][^"']*["']/gi, ""); return safe; },});// Usage — innerHTML assignments must go through the policyconst el = document.getElementById("content")!;el.innerHTML = sanitizePolicy.createHTML(userContent);// Without the policy, the browser throws a TypeError
Trusted Types is a newer browser API that locks down DOM XSS sinks (innerHTML, document.write, insertAdjacentHTML, etc.). When enabled via CSP (require-trusted-types-for 'script'), the browser throws a TypeError if any code tries to pass a string to these sinks without going through a registered policy. This catches XSS even if an attacker bypasses your sanitization logic.
SQL injection — parameterized queries
sql-injection.tstypescript
// ❌ Vulnerable — string concatenationconst query = `SELECT * FROM users WHERE email = '${userInput}'`;// Input: ' OR '1'='1 → SELECT * FROM users WHERE email = '' OR '1'='1'// Returns ALL users — authentication bypass!// ✅ Safe — parameterized query (Prisma / Knex / pg prepared statements)const user = await prisma.user.findUnique({ where: { email: userInput },});// ✅ Safe — parameterized SQL with node-postgresconst { rows } = await pool.query( "SELECT * FROM users WHERE email = $1", [userInput],);
The rule is simple: never concatenate user input into SQL strings. Use parameterized queries (Prisma, Knex, prepared statements) or an ORM that handles escaping for you. This is not just a backend concern — if your API route constructs SQL from query parameters, you are vulnerable.
OAuth 2.1 + PKCE
oauth-pkce.tstypescript
// PKCE (Proof Key for Code Exchange) — OAuth 2.1 flow// Prevents authorization code interception attack// Step 1: Generate code verifier and challengefunction generatePKCE() { const verifier = base64URLEncode(crypto.getRandomValues(new Uint8Array(32))); const challenge = base64URLEncode( crypto.subtle.digestSync("SHA-256", new TextEncoder().encode(verifier)), ); return { verifier, challenge };}// Step 2: Redirect to auth server with challengeconst { verifier, challenge } = generatePKCE();const authUrl = `https://auth.example.com/authorize? response_type=code& client_id=${CLIENT_ID}& redirect_uri=${REDIRECT_URI}& code_challenge=${challenge}& code_challenge_method=S256& state=${state}`;// Step 3: Exchange code using verifier (never exposed to browser)const tokenResponse = await fetch("https://auth.example.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code: authCode, redirect_uri: REDIRECT_URI, code_verifier: verifier, // stored server-side, never in URL }),});
If you implement OAuth, use the authorization code flow with PKCE (Proof Key for Code Exchange). PKCE prevents the authorization code interception attack, where a malicious application intercepts the authorization code from the callback URL. The code_verifier is stored server-side and never exposed to the browser.
6 · Under the Hood
Let me show you what happens inside the browser and server when an attacker attempts a CSRF attack against a protected application. Understanding the internal mechanics — the sequence of header checks, token validations, and browser policy evaluations — is what separates theoretical knowledge from practical defense.
Debug trace: CSRF attack prevented
Imagine a user is logged into bank.example.com and visits evil.com. A hidden form on evil.com tries to POST to bank.example.com/api/transfer. Here is the exact sequence of checks:
1. Browser sends POST to bank.example.com/api/transfer
Origin: https://evil.com ← browser sets this automatically
Cookie: sessionid=abc123 ← browser includes cookie (cross-site)
2. Server receives request:
┌─ CORS check ──────────────────────────────┐
│ Origin 'evil.com' NOT in allowlist → 403 │
│ But wait — CORS is permissive? → continue │
└───────────────────────────────────────────┘
┌─ CSRF token check ────────────────────────┐
│ X-CSRF-Token header: MISSING │
│ → 403 Forbidden, log CSRF violation │
└───────────────────────────────────────────┘
┌─ SameSite cookie check ───────────────────┐
│ Cookie: SameSite=Lax │
│ POST from cross-site → cookie NOT sent │
│ → Session lookup fails → 401 Unauthorized │
└───────────────────────────────────────────┘
3. Response: 403 Forbidden (defense won)
Even if the attacker manages to bypass one check (say, the origin passes CORS because the server is misconfigured), the SameSite cookie still blocks the session cookie from being sent on a cross-site POST. This is defense in depth in action.
Call stack: CSP violation report
When CSP blocks a resource, the browser fires a SecurityPolicyViolationEvent. Here is the call chain:
HTMLScriptElement.appendChild()
└─ ScriptLoader::prepareScript()
└─ ContentSecurityPolicy::allowInlineScript()
├─ Check 'unsafe-inline' in script-src? NO
├─ Check nonce match? NO
├─ Check hash match? NO
└─ → BLOCKED. Fire violation event.
└─ CSPViolationReporter::queueReport()
└─ POST to report-uri endpoint
└─ Server logs: {
"document-uri": "https://bank.example.com/dashboard",
"violated-directive": "script-src 'self'",
"blocked-uri": "inline",
"line-number": 42,
"source-file": "https://evil.com/inject.js"
}
The violation report includes the exact line number and source file of the blocked resource. I log these reports to a dedicated endpoint that alerts the security team. A sudden spike in CSP violations is often the first sign of an active XSS probe.
Figure 3 — CSRF attack vs. legitimate request. CSRF tokens, SameSite cookies, Origin header checks, and CORS policy form a multi-layered defense.
7 · Data Flow & Communication
Tracing a complete secure interaction helps connect the dots between the different security subsystems. Here is what happens when a user logs in and performs a protected action:
TLS handshake (TCP → TLS 1.3)
Client connects to server. TLS 1.3 handshake negotiates encryption. All subsequent data is encrypted. HSTS header tells browser to always use HTTPS.
Login — password verification
POST /api/login with credentials. Server validates input, verifies bcrypt hash, creates session. Response sets Set-Cookie with HttpOnly+Secure+SameSite=Lax.
CSRF token delivery
After login, the client fetches /api/csrf-token. The server generates an HMAC of the session ID and returns it. The token is stored in a meta tag or a non-persistent variable.
Protected action (POST /api/transfer)
Client sends POST with X-CSRF-Token header. Cookie sent with SameSite=Lax rules. Server validates CSRF token (constant-time compare), checks session, verifies origin. If all pass: execute. If any fail: 403.
Response delivered under CSP
Server responds with HTML + CSP header. Browser enforces script-src, style-src, frame-ancestors. Any inline script without a valid nonce is blocked. CSP violation reports are sent to report-uri.
Audit log written
Server writes an audit record: timestamp, user ID, action, IP, user-agent, outcome. This log is append-only and sent to a separate logging pipeline (not the application database).
Notice that every layer has a fallback. If the CSRF token check fails (misconfigured middleware), the SameSite cookie check still blocks cross-site POST requests. If the CSP header is stripped by a misconfigured reverse proxy, Trusted Types (if enabled client-side) still blocks DOM-based XSS. No single failure exposes the application.
8 · Performance Optimization
Security controls have a cost. The key is to understand which ones are negligible and which ones require architectural consideration.
Negligible cost (accept unconditionally)
HTTP headers: CSP, HSTS, X-Frame-Options, etc. add zero measurable latency — they are set once per response and add a few hundred bytes to the header size.
SameSite cookies: The browser enforces this locally — no network overhead.
React JSX escaping: Already part of the render pipeline. No additional cost.
Measurable cost (optimize carefully)
Bcrypt hashing (~250ms at cost 12): Acceptable for login/register (users expect a delay). Never use on per-request middleware. Cache the hash result if the same user authenticates repeatedly within a session.
CSRF token generation: A single SHA-256 hash is ~1μs. Negligible. The real cost is the session lookup, which you need anyway for authentication.
Rate limiting (TokenBucket): O(1) per check, in-memory. With Redis backend, add ~1ms network latency per request. Batch decrement operations to reduce round trips.
DOMPurify sanitization: ~50μs for typical input. Only call it on inputs that need rich HTML (comments, blog posts). Plain text fields skip sanitization entirely.
Tradeoff table
Control
Cost
Threat Mitigated
CSP header
~0ms (response header)
XSS, data injection, clickjacking
Bcrypt (cost 12)
~250ms per hash
Password brute force
CSRF token validation
~1μs + session lookup
Cross-site request forgery
TokenBucket rate limiter
O(1) in-memory, ~1ms with Redis
Brute force, DDoS, abuse
DOMPurify sanitization
~50μs per input
Stored XSS via rich content
TLS 1.3
~1 RTT handshake (0-RTT resumption)
Eavesdropping, MITM, tampering
9 · Security Considerations
This article is about security, so the security section is a meta-discussion: what are the common failure modes of the defenses themselves?
CSP bypass via JSONP endpoints: If your CSP includes script-src 'self' and your application has a JSONP endpoint (a common pattern in legacy apps), an attacker can use it to inject arbitrary scripts. The fix: remove JSONP endpoints or use a nonce-based CSP.
CSRF token leakage via referrer header: When a user clicks a link on your page to navigate to an external site, the browser sends the Referer header containing the full URL — including any query parameters or fragment that might contain the CSRF token. Use Referrer-Policy: same-origin or pass the CSRF token via a custom header instead of a query parameter.
Rate limiter bypass via IP rotation: An attacker using a botnet can rotate through thousands of IP addresses. IP-based rate limiting is insufficient — combine it with behavioral analysis (rate of failed logins per user account, not just per IP).
Timing attacks on token comparison: A naive string comparison (===) short-circuits on the first mismatched byte. An attacker can measure response times to determine how many bytes of the token they guessed correctly. Always use crypto.timingSafeEqual for token and hash comparisons.
Dependency supply chain: Your security is only as strong as your weakest dependency. A compromised npm package can bypass all application-level security. Use "npm audit", lockfiles (pnpm-lock.yaml), and SRI for third-party CDN resources. Consider npm-package-json-lint to enforce minimum dependency age and audit status.
Developer error (the most common failure): A developer disables a security check "temporarily" and forgets to re-enable it. Use lint rules ( eslint-plugin-security, no-dangerouslySetInnerHTML) and automated header checks in CI to catch these regressions.
Key Insight
The most dangerous vulnerability is the one you create yourself while trying to fix another. Security controls interact in unexpected ways: a developer who cannot get CSP to work with their analytics script might set script-src: *, which bypasses the entire policy. Document each control's purpose and failure mode so your teammates understand why it exists.
10 · Testing Strategy
Security testing is not the same as feature testing. You cannot write a unit test that proves XSS is impossible — you can only test specific scenarios and verify that the defense mechanisms are present and functional.
Render test with script injection: Render a component with <script>alert(1)</script> as input. Assert that the output does not contain <script> in the DOM. Use screen.getByText to verify the text is present but the script is not executed.
DOMPurify bypass suite: Test known DOMPurify bypass vectors. The DOMPurify project maintains a list of regression tests. Include the top 10 in your test suite and update them when you upgrade the library.
dangerouslySetInnerHTML audit: A CI lint rule that flags every occurrence of dangerouslySetInnerHTML. Each occurrence must have a code comment justifying why sanitization is handled correctly. I use eslint-plugin-react with no-danger and no-danger-with-children.
CSRF-specific tests
Missing token test: Send a POST request without the X-CSRF-Token header. Assert 403 response.
Invalid token test: Send a POST request with an invalid token. Assert 403.
Cross-origin test: Send a POST request with Origin: https://evil.com. Assert 403.
GET should not require CSRF: Send a GET request without a token. Assert 200 (GET requests should not perform state changes).
Integration and E2E tests
Use security-focused scanning tools in your CI pipeline. I run three:
ZAP (Zed Attack Proxy): An OWASP DAST tool that crawls your application and tests for common vulnerabilities. Run it as a CI step against your staging environment.
securityheaders.com: A quick external check for HTTP security headers. I include this in the deployment pipeline to verify headers are present in production.
npm audit / pnpm audit: Run on every build. Fail the pipeline on critical or high severity vulnerabilities.
Note
Security tests are regression detectors, not proofs of security. A passing test suite does not mean your application is secure — it means the specific scenarios you tested are covered. New vulnerabilities are discovered every day. Treat your test suite as a living document that evolves alongside the threat landscape.
11 · Accessibility
Security and accessibility can conflict. Here is how I reconcile them.
CAPTCHA vs. accessibility
Visual CAPTCHAs (distorted text, image selection) are inaccessible to blind users and difficult for users with cognitive disabilities. Audio CAPTCHAs are hard for users with hearing impairments. The best alternative is a behavioral analysis system (e.g., Cloudflare Turnstile, hCaptcha accessibility mode) that requires no user interaction. If you must use a visual CAPTCHA, provide an audio alternative and a text-based alternative (e.g., a simple math problem).
Session timeout notifications
When a session is about to expire, notify the user with a visible, screen-reader-accessible message. Use a role="alert" live region that announces the timeout at least 60 seconds before it happens. Provide a "Keep me signed in" button that does not require mouse interaction.
Rate limiting error messages
When a user is rate limited, the error message must not reveal whether the account exists (that would leak information to attackers probing for valid usernames). Use a generic message: "Too many attempts. Please try again later." The message should be announced by screen readers but should not include the retry time (which attackers could use to calibrate their rate).
Focus management on error
When a security error occurs (failed CSRF, expired session), move focus to the error message or the login form. Do not rely on color alone to indicate the error state — use text, icons, and ARIA attributes.
12 · Live Demo
Security is hard to demonstrate in a playground because the defenses are invisible when they work. But you can see them in action:
Open your browser's Developer Tools → Network tab and inspect the response headers on any page. You should see Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, and Referrer-Policy.
Look at the Set-Cookie header in a login response. It should include HttpOnly, Secure, and SameSite attributes.
Try to submit a form without the CSRF token. The server should return 403. Try to POST from a different origin — the CORS preflight should block it.
Open the Console tab and look for CSP violation reports. Every blocked inline script produces a warning.
Figure 4 — Essential HTTP security headers. Every production app should serve at minimum CSP, HSTS, X-Frame-Options, X-Content-Type-Options, and Secure+HttpOnly+SameSite cookies.
For a hands-on test, visit your application on securityheaders.com and the Mozilla Observatory. These tools scan your site and give you a security rating (A+ is the goal) with specific recommendations for improvement.
13 · Key Takeaways
Defense in depth is non-negotiable. No single security control is sufficient. Layer CSP on top of output encoding on top of input validation on top of HTTPS. Each layer catches what the others miss.
CSP is your most powerful browser-level defense. A well-configured CSP blocks XSS, clickjacking, data injection, and mixed content. Deploy it in report-only mode first, monitor violations, then enforce.
Use HttpOnly + Secure + SameSite on every cookie. These three attributes prevent cookie theft via XSS, accidental HTTP transmission, and most CSRF attacks. Set them by default and only relax them when you have a documented reason.
Parameterized queries are mandatory. No excuses. Every ORM in every language supports them. If you are concatenating strings to build SQL, you are vulnerable to SQL injection.
Rate limiting protects against abuse, not just attacks. A token bucket rate limiter with per-user and per-IP buckets prevents brute force login attempts, API abuse, and scraping. Cost: O(1) per check.
Test security headers in CI. Write a test that fetches every route and asserts the presence of CSP, HSTS, X-Frame-Options, and X-Content-Type-Options. Run it on every deploy. A missing header is a regression.
Bcrypt (or Argon2) for passwords, not SHA-256. Fast hash functions are designed for speed — they are terrible for password storage. Use a slow, adaptive hash function with a salt.
Trusted Types prevent DOM-based XSS at the browser level. Enable them via CSP and create a policy for the few legitimate uses of innerHTML. The browser enforces the policy, not your code.
I have been doing frontend security for years, and I still make mistakes. The difference between a secure application and an insecure one is not the absence of mistakes — it is the presence of multiple layers of defense that catch those mistakes before they become breaches. Apply defense in depth, test your headers, and never trust user input.