Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
CSP is an HTTP security header that restricts which resources (scripts, styles, images, etc.) can be loaded on your web page. It's a powerful defense against XSS attacks, data injection, and clickjacking.
Blocks inline scripts and unsafe eval()
Only approved sources can load resources
Get notified of policy violations
Fallback for all resource types
default-src 'self';Controls JavaScript sources
script-src 'self' cdn.example.com;Controls CSS stylesheets
style-src 'self' 'unsafe-inline';Controls image sources
img-src 'self' data: https:;Controls AJAX, WebSocket, fetch
connect-src 'self' api.example.com;Prevents clickjacking
frame-ancestors 'none';// Node.js/Express - Set CSP header
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' https://cdn.jsdelivr.net; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"font-src 'self' https://fonts.gstatic.com; " +
"connect-src 'self' https://api.example.com; " +
"frame-ancestors 'none'; " +
"base-uri 'self'; " +
"form-action 'self'"
);
next();
});
// Or use helmet.js middleware
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://cdn.jsdelivr.net"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://api.example.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
}
}));Resources from same origin (same protocol, domain, port)
Block all sources (nothing allowed)
⚠️ Allows inline scripts/styles (defeats purpose of CSP, avoid if possible)
⚠️ Allows eval() and similar functions (dangerous, avoid)
✅ Allow specific inline scripts with matching nonce attribute
✅ Allow specific inline script by its hash
// Backend: Generate nonce per request
const crypto = require('crypto');
app.use((req, res, next) => {
// Generate random nonce
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
// Set CSP with nonce
res.setHeader(
'Content-Security-Policy',
`default-src 'self'; script-src 'self' 'nonce-${res.locals.cspNonce}'`
);
next();
});
// HTML template: Use nonce attribute
<script nonce="<%= cspNonce %>">
// This inline script is allowed!
console.log('Script with valid nonce');
</script>
<script>
// This will be BLOCKED (no nonce)
console.log('Blocked!');
</script>
// React/Next.js example
export default function Page() {
const nonce = headers().get('x-nonce'); // Get from headers
return (
<html>
<head>
<script nonce={nonce}>
{/* Inline script allowed with nonce */}
</script>
</head>
</html>
);
}// Use Content-Security-Policy-Report-Only for testing
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy-Report-Only',
"default-src 'self'; " +
"script-src 'self'; " +
"report-uri /csp-violation-report" // Where to send violations
);
next();
});
// Endpoint to receive violation reports
app.post('/csp-violation-report', express.json({ type: 'application/csp-report' }), (req, res) => {
const violation = req.body;
console.log('CSP Violation:', {
blockedURI: violation['blocked-uri'],
violatedDirective: violation['violated-directive'],
documentURI: violation['document-uri'],
lineNumber: violation['line-number'],
sourceFile: violation['source-file']
});
// Log to monitoring service
// logger.warn('CSP violation detected', violation);
res.status(204).end();
});
// Modern alternative: report-to directive
res.setHeader('Report-To', JSON.stringify({
group: "csp-endpoint",
max_age: 10886400,
endpoints: [{ url: "https://example.com/csp-reports" }]
}));
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; report-to csp-endpoint"
);CSP is a powerful XSS defense layer
Complements input validation
Prefer nonces over 'unsafe-inline'
Secure way to allow inline scripts
Use Report-Only to test
Track CSP violations
Only allow trusted domains
Avoid wildcards for scripts