JAVASCRIPT
Implementing a Strict Content Security Policy (CSP) with Helmet.js
Secure your web application against XSS, clickjacking, and other injection attacks by configuring a robust Content Security Policy using Helmet.js middleware in Express.
const express = require('express');
const helmet = require('helmet');
const app = express();
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", 'https://trusted-scripts.com'], // Be very careful with 'unsafe-inline'
styleSrc: ["'self'", "'unsafe-inline'", 'https://trusted-styles.com'],
imgSrc: ["'self'", 'data:', 'https://cdn.example.com'],
connectSrc: ["'self'", 'https://api.example.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
// reportUri: '/csp-violation-report-endpoint', // Uncomment to enable reporting
},
}));
app.get('/', (req, res) => {
res.send('Hello with CSP!');
});
app.listen(3000, () => {
console.log('App listening on port 3000 with CSP!');
});
How it works: This snippet demonstrates how to implement a Content Security Policy (CSP) using the Helmet.js middleware in an Express.js application. CSP is a powerful security layer that helps mitigate XSS and data injection attacks by specifying which sources of content are allowed to be loaded by the browser. The `directives` object defines rules for different types of resources (scripts, styles, images, etc.), with `'self'` allowing resources from the same origin, and specific URLs or `'none'` for stricter control. Using `'unsafe-inline'` for scripts/styles should be avoided if possible, or used with extreme caution, as it weakens CSP protection. For production, consider enabling `reportUri` to log violations.