JAVASCRIPT
Implementing a Robust Content Security Policy (CSP) in Express.js
Fortify your Express.js application against XSS and data injection attacks by configuring a strong Content Security Policy (CSP) header to control resource loading.
const express = require('express');
const helmet = require('helmet'); // Recommended for security headers
const app = express();
// Use Helmet to set various security headers, including CSP
// Customize the CSP based on your application's needs
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"], // Only allow resources from the same origin
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", "https://trusted-cdn.com"], // Allow scripts from self, inline, eval (if absolutely necessary), and trusted CDN
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], // Allow styles from self, inline, and Google Fonts
imgSrc: ["'self'", "data:", "https://img.example.com"], // Allow images from self, data URIs, and example image host
connectSrc: ["'self'", "wss://your-websocket.com", "https://api.example.com"], // Allow XHR/WebSockets to self, your WebSocket server, and trusted API
fontSrc: ["'self'", "https://fonts.gstatic.com"], // Allow fonts from self and Google Fonts
objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
frameSrc: ["'self'", "https://www.youtube.com"], // Allow iframes from self and YouTube
// reportUri: "/csp-violation-report-endpoint", // Optional: send violation reports to this endpoint
},
// Optionally, set reportOnly to true during development to test without blocking
// reportOnly: true,
}));
app.get('/', (req, res) => {
res.send('<h1>Hello, secure web!</h1><script>alert("This inline script will be blocked unless unsafe-inline is specified for scriptSrc");</script>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running securely on port ${PORT}`);
});
// To run:
// 1. npm init -y
// 2. npm install express helmet
// 3. Save as app.js and run `node app.js`
How it works: This Express.js snippet demonstrates how to implement a Content Security Policy (CSP) using the `helmet` middleware. A CSP is a crucial security layer that helps mitigate XSS and other client-side injection attacks by restricting which resources (scripts, styles, images, etc.) a browser is allowed to load and execute. The `directives` object defines granular rules, such as `defaultSrc` for a baseline, `scriptSrc` for allowed script sources, and `objectSrc: ["'none'"]` to block plugins. By carefully configuring CSP, developers can significantly reduce the attack surface of their web applications.