javascript / intermediate
Snippet
Secure Third-Party Script Injection with Nonce Verification
Injecting dynamic external scripts in web applications presents security risks if left unverified. Utilizing Subresource Integrity (SRI) hashes alongside Content Security Policy (CSP) nonces guarantees that external scripts have not been tampered with and adhere to strict server security policies.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
export function loadSecureScript(url, integrityHash, cspNonce) {return new Promise((resolve, reject) => {const script = document.createElement('script');script.src = url;script.integrity = integrityHash;script.crossOrigin = 'anonymous';if (cspNonce) script.setAttribute('nonce', cspNonce);script.onload = () => resolve(true);script.onerror = () => reject(new Error(`Failed script load: ${url}`));document.head.appendChild(script);});}
svelte
Breakdown
1
script.integrity = integrityHash;
Assigns a cryptographic hash that the browser verifies against the downloaded script file to prevent tampering.
2
script.crossOrigin = 'anonymous';
Configures CORS mode to enable cross-origin fetch integrity verification without sending user credentials.
3
if (cspNonce) script.setAttribute('nonce', cspNonce);
Attaches a cryptographic server nonce to pass strict Content Security Policy script-execution restrictions.
4
script.onerror = () => reject(new Error(`Failed script load: ${url}`));
Handles loading failures asynchronously by rejecting the Promise with an explicit error object.