Content Security Policy Violation
The browser blocked a resource because it violated the Content Security Policy.
Explanation
Content Security Policy (CSP) violation occurs when the browser blocks a resource (script, style, image, font, etc.) because it doesn't comply with the Content-Security-Policy header or meta tag. CSP is a security layer that prevents XSS attacks by restricting which resources can be loaded. Common violations include loading scripts from unauthorized domains, inline scripts (when not allowed), eval(), loading images from external sources, and using web fonts from CDN without authorization.
Common Causes
- Loading scripts from unauthorized domains
- Inline scripts without nonce/hash
- Using eval() or Function()
- Loading images/fonts from external CDN
- Third-party scripts loading unauthorized resources
Solution
Review the CSP error in the browser console to identify which resource was blocked. Update the CSP header to allow the specific domains and resource types needed. Use nonces or hashes for inline scripts instead of allowing all inline. For development, use Content-Security-Policy-Report-Only to test without blocking. Check for third-party scripts that might load resources from unexpected domains. Use CDN configuration to serve resources from your domain. Consider using the report-uri directive to monitor violations.
Code Example
// CSP header that blocks resources
Content-Security-Policy: default-src 'self'; script-src 'self';
// This inline script is blocked
<script>
console.log('blocked!'); // inline not allowed!
</script>
// Fix: use nonce
<script nonce="random123">
console.log('allowed!');
</script>
// Laravel CSP middleware
// Add to response headers:
$policy = [
"default-src 'self'",
"script-src 'self' 'nonce-{$nonce}' https://cdn.example.com",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self' https://fonts.gstatic.com",
];
header('Content-Security-Policy: ' . implode('; ', $policy));
// Development: report-only mode
header('Content-Security-Policy-Report-Only: ...');
// Allow inline in Next.js next.config.js
module.exports = {
headers: async () => [{
source: '/:path*',
headers: [{
key: 'Content-Security-Policy',
value: "script-src 'self' 'unsafe-eval' 'unsafe-inline'"
}]
}]
};
Error Information
Language
javascript
Difficulty
Intermediate
Views
234
Related Errors
ECONNREFUSED
Database
ECONNREFUSED
The network connection was refused by the target server.
JavaScript
RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.
JavaScript
SyntaxError: Unexpected Token
JavaScript parser encountered a token it didn't expect at that position.
JavaScript
TypeError: X is not a function
The code tries to call a value as a function, but it's not a function.