Back to cheatsheets
Web Security
CSP Evaluation & Hardening
Parse Content-Security-Policy directives, detect unsafe-inline/unsafe-eval, and harden your CSP.
What you'll learn
- Parse CSP directives
- Nonce-based CSP (recommended)
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for csp evaluation & hardening. Click copy and paste into your project.
Parse CSP directives
function parseCSP(header) {
const directives = {};
header.split(';').forEach(part => {
const [name, ...values] = part.trim().split(/\s+/);
directives[name] = values;
});
return directives;
}
// Check for dangerous directives
function auditCSP(csp) {
const issues = [];
if (csp['script-src']?.includes("'unsafe-inline'"))
issues.push('unsafe-inline in script-src');
if (csp['script-src']?.includes("'unsafe-eval'"))
issues.push('unsafe-eval in script-src');
if (!csp['default-src'])
issues.push('Missing default-src fallback');
return issues;
}
Nonce-based CSP (recommended)
// Generate per-request nonce
const nonce = crypto.randomUUID();
// Set header
res.setHeader('Content-Security-Policy',
`default-src 'self'; ` +
`script-src 'self' 'nonce-${nonce}'; ` +
`style-src 'self' 'nonce-${nonce}'`);
// Use in HTML
// <script nonce="{nonce}">...</script>
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site