JAVASCRIPT
Implement Content Security Policy (CSP) for XSS Defense
Secure your web application against XSS attacks by implementing a strong Content Security Policy (CSP) header in your Node.js Express server.
const express = require('express');
const app = express();
const port = 3000;
app.use((req, res, next) => {
// Define your CSP rules
const cspHeader = "default-src 'self';" +
"script-src 'self' https://trusted.cdn.com;" +
"style-src 'self' 'unsafe-inline' https://trusted.cdn.com;" +
"img-src 'self' data: https://trusted.images.com;" +
"font-src 'self' https://trusted.fonts.com;" +
"object-src 'none';" +
"base-uri 'self';" +
"form-action 'self';" +
"frame-ancestors 'self';" +
"upgrade-insecure-requests;"; // Automatically upgrade HTTP requests to HTTPS
res.setHeader('Content-Security-Policy', cspHeader);
next();
});
app.get('/', (req, res) => {
res.send('<h1>CSP Enabled Page</h1><script>alert("Hello!")</script><style>h1 { color: blue; }</style>');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to implement a Content Security Policy (CSP) by setting the `Content-Security-Policy` HTTP header. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) attacks by allowing web developers to control which resources (scripts, stylesheets, images, etc.) the browser is allowed to load and execute. The `cspHeader` string defines various directives, such as `default-src 'self'` which restricts all resources to the same origin, and specific directives like `script-src` and `style-src` to permit scripts and styles only from trusted sources or inline styles (if explicitly allowed with 'unsafe-inline' - use with caution). Directives like `object-src 'none'` completely disable certain features, enhancing security.