Skip to content

XSS Defense in React & Next.js: DOM & CSP

Defend against Stored, Reflected, and DOM Cross-Site Scripting (XSS) in React, Next.js, and Vue using safe DOM sinks, sanitization, and CSP headers.

By BugSnaps Security Research · 2 min read · Updated

Add BugSnaps as a preferred source on Google(opens in a new tab)

Want more of our security guides? Select BugSnaps and confirm your choice on Google.

Cross-Site Scripting (XSS) occurs when an application renders untrusted input in a browser context where it executes as JavaScript. When an XSS payload runs inside a victim's origin, it can issue authenticated API requests, read accessible DOM state, or alter page content on the user's behalf.

Where XSS still happens in React, Next.js, and Vue

Modern frontend frameworks automatically escape text rendered inside standard JSX or template bindings (`{userComment}`). However, XSS still appears in Single Page Applications whenever code bypasses default text escaping or passes user-controlled URLs into executable browser sinks:

  • Raw HTML rendering APIs: passing unsanitized markdown, CMS content, or rich text into React's `dangerouslySetInnerHTML` or Vue's `v-html` without running a configured HTML sanitizer such as DOMPurify.
  • Unvalidated `javascript:` or `data:` URLs: binding user-supplied profile links or redirect targets directly into `<a href={userUrl}>` or `window.location.assign(url)` without verifying that the parsed protocol is `https:` or `http:`.
  • Unsafe DOM and script sinks: passing query parameters, `location.hash`, or `postMessage` payloads into `eval()`, `Function()`, `Element.innerHTML`, or `document.write()`.
  • Uploaded SVG and HTML files: serving user-uploaded `.svg` or `.html` files inline from the main application origin rather than an isolated storage domain with `Content-Disposition: attachment`.

Layering output encoding, HttpOnly cookies, and CSP

Effective XSS defense relies on three independent layers. First, sanitize any unavoidable rich HTML with a strict allowlist of tags and attributes, and validate URL schemes via the `new URL()` parser before rendering links. Second, mark session cookies as `HttpOnly` so that even if a script executes, it cannot read raw session cookies via `document.cookie`.

Third, deploy a Content-Security-Policy (CSP) header that restricts script execution to trusted origins or per-request cryptographic nonces (`script-src 'self' 'nonce-...'`) and blocks inline event handlers. Pairing context-aware framework rendering with CSP and `HttpOnly` cookies turns potential XSS bugs into blocked browser violations.

Audit every use of dangerouslySetInnerHTML and dynamic href attributes, keep session cookies HttpOnly, and enforce a Content-Security-Policy header.

Run a vulnerability scan on your website.

Verify your domain and use MyPentest to check for supported web and API weaknesses. Review findings and coverage; a clean scan does not rule out every CVE.