JAVASCRIPT
Enforce Strict Content Security Policy (CSP) in Express.js
Secure your web application against XSS attacks by implementing a strong Content Security Policy (CSP) header in Express.js, restricting script and resource sources.
const express = require('express');
const helmet = require('helmet'); // Recommended for setting security headers
const app = express();
// Use helmet to set various security headers, including CSP
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"], // Only allow resources from the same origin
scriptSrc: ["'self'", "'unsafe-inline'", "cdn.example.com"], // Allow scripts from self and a specific CDN
styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com"], // Allow styles from self and Google Fonts
imgSrc: ["'self'", "data:", "images.example.com"], // Allow images from self, data URIs, and specific image domain
fontSrc: ["'self'", "fonts.gstatic.com"], // Allow fonts from self and Google Fonts
connectSrc: ["'self'", "api.example.com"], // Allow fetch/XHR to self and specific API domain
objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
frameSrc: ["'none'"], // Disallow framing of the page
upgradeInsecureRequests: [], // Clients supporting CSP Level 2+ will rewrite HTTP requests to HTTPS
},
}));
app.get('/', (req, res) => {
res.send('<h1>Hello, CSP!</h1>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement a robust Content Security Policy (CSP) in an Express.js application using the `helmet` middleware. CSP helps mitigate Cross-Site Scripting (XSS) and other code injection attacks by specifying allowed sources for various content types, such as scripts, stylesheets, and images. The `directives` object defines granular rules, preventing browsers from loading unauthorized resources and enhancing the application's overall security posture.