JAVASCRIPT
Implementing a Strong Content Security Policy (CSP)
Protect your web application from XSS and data injection by configuring a robust Content Security Policy (CSP) HTTP header using Helmet in an Express.js application.
const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers
const app = express();
// Use Helmet's CSP middleware
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"], // Only allow resources from the same origin by default
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", "https://trusted-cdn.com"], // Allow self, specific inline scripts/evals, and a trusted CDN
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], // Allow self, specific inline styles, and Google Fonts
imgSrc: ["'self'", "data:", "https://img.example.com"], // Allow self, data URIs, and a specific image host
fontSrc: ["'self'", "https://fonts.gstatic.com"], // Allow self and Google Fonts
objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
baseUri: ["'self'"], // Restrict base URI
formAction: ["'self'"], // Restrict form submissions to self
frameAncestors: ["'none'"], // Prevent clickjacking (e.g., via iframes)
upgradeInsecureRequests: [], // Automatically upgrade insecure HTTP requests to HTTPS
blockAllMixedContent: [], // Block all insecure HTTP requests on HTTPS pages
},
})
);
app.get('/', (req, res) => {
res.send('<h1>Hello, Secure Web!</h1><script>console.log("This script is allowed if inline scripts are enabled or a hash/nonce is used.");</script>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log('Check network tab in browser for Content-Security-Policy header.');
});
// To run:
// 1. npm init -y
// 2. npm install express helmet
// 3. node your_file_name.js
How it works: This Node.js (Express) snippet demonstrates how to implement a robust Content Security Policy (CSP) using the `helmet` middleware. CSP is an HTTP security header that helps prevent Cross-Site Scripting (XSS) and other code injection attacks by specifying allowed sources for various content types (scripts, styles, images, etc.). The example configures directives like `defaultSrc`, `scriptSrc`, and `objectSrc` to define a whitelist of trusted content sources, significantly reducing the attack surface. It also includes directives like `upgradeInsecureRequests` and `blockAllMixedContent` for enforcing HTTPS, and `frameAncestors` to prevent clickjacking.