javascript / expert
Snippet
Injecting Dynamic CSP Nonces via React Context for Inline Script Validation
To prevent Cross-Site Scripting (XSS) when rendering dynamic inline scripts in React applications, Content Security Policy (CSP) cryptographic nonces must be securely propagated down the component tree. Using React Context combined with custom hooks ensures that every dynamically generated script tag explicitly requires and validates a cryptographically secure nonce before rendering.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { createContext, useContext, useId } from 'react';const NonceContext = createContext<string | null>(null);export const NonceProvider: React.FC<{ nonce: string; children: React.ReactNode }> = ({ nonce, children }) => (<NonceContext.Provider value={nonce}>{children}</NonceContext.Provider>);export const useSafeScript = (scriptContent: string) => {const nonce = useContext(NonceContext);if (!nonce) throw new Error('Security Violation: Missing CSP Nonce context provider.');return {dangerouslySetInnerHTML: { __html: scriptContent },nonce};};
react
Breakdown
1
const NonceContext = createContext<string | null>(null);
Establishes a strongly-typed React context to hold the server-generated CSP nonce string.
2
if (!nonce) throw new Error('Security Violation: Missing CSP Nonce context provider.');
Enforces a hard security boundary that halts rendering if an inline script attempts to execute without an authenticated CSP nonce.
3
nonce
Binds the valid cryptographic nonce attribute directly to the returned element property object.