How to Fix Helmet.js Content Security Policy Blocking Resources Error
In this tutorial, you'll learn about How to Fix Helmet.js Content Security Policy Blocking Resources Error. We cover key concepts, practical examples, and best practices.
The Problem
Your browser console shows:
Refused to load the script 'https://cdn.example.com/lib.js' because it violates the following Content Security Policy directive: "script-src 'self'".
Or:
Refused to execute inline script because it violates the following Content Security Policy directive
Helmet.js applies strict Content Security Policy (CSP) headers that block resources from external sources or inline scripts.
Quick Fix
1. Add external sources to the CSP
// Wrong — default CSP blocks all external resources
const helmet = require('helmet')
app.use(helmet())
// Right — configure CSP with allowed sources
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://cdn.example.com", "https://analytics.example.com"],
styleSrc: ["'self'", "https://fonts.googleapis.com"],
imgSrc: ["'self'", "https://images.example.com", "data:"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
connectSrc: ["'self'", "https://api.example.com"],
frameSrc: ["'self'"],
objectSrc: ["'none'"],
upgradeInsecureRequests: []
}
})
)
2. Use nonces for inline scripts
For inline <script> tags, add a nonce (number used once):
// Server — generate nonce per request
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString('base64')
next()
})
app.use(
helmet.contentSecurityPolicy({
directives: {
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
// Other directives...
}
})
)
<!-- Template — add nonce to inline scripts -->
<script nonce="{{nonce}}">
// This inline script is now allowed
console.log('CSP allows this')
</script>
3. Use 'unsafe-inline' sparingly (not recommended)
// Not recommended — but works for quick fixes
app.use(
helmet.contentSecurityPolicy({
directives: {
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"]
}
})
)
This disables the inline script/style protection. Use nonces or hashes instead.
4. Use CSP report-only mode for testing
// Report-only — blocks nothing, reports violations
app.use(
helmet.contentSecurityPolicy({
useDefaults: false,
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"]
},
reportOnly: true, // won't block, just reports
reportUri: '/csp-violation'
})
)
// Receive violation reports
app.post('/csp-violation', (req, res) => {
console.log('CSP violation:', req.body)
res.status(204).end()
})
5. Check for inline styles from frameworks
React, Vue, and other frameworks often inject inline styles:
// React with styled-components needs style-src 'unsafe-inline'
// or use a nonce approach
app.use(
helmet.contentSecurityPolicy({
directives: {
styleSrc: ["'self'", "'unsafe-inline'"] // needed for many CSS-in-JS libraries
}
})
)
6. Whitelist specific CDN or external resources
Find the exact source being blocked from the console error:
// Check the console for:
// "Refused to load ... because it violates ... Content Security Policy"
// Then add the specific domain:
app.use(
helmet.contentSecurityPolicy({
directives: {
scriptSrc: ["'self'", "https://code.jquery.com", "https://stackpath.bootstrapcdn.com"],
styleSrc: ["'self'", "https://stackpath.bootstrapcdn.com"],
imgSrc: ["'self'", "https://via.placeholder.com"]
}
})
)
Prevention
- Set up CSP report-only mode during development to discover violations.
- Use nonces or hashes instead of 'unsafe-inline' when possible.
- Review external resource dependencies and consolidate them.
- Use a CSP generator tool to build policies from your actual resource usage.
- Monitor CSP violation reports after deployment.
- Keep CSP as strict as your application allows.
Common Mistakes with js error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world HELMET code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro