JAVASCRIPT

Implementing a Content Security Policy (CSP) Header in Node.js Express

Protect your web application from Cross-Site Scripting (XSS) and data injection attacks by implementing a robust Content Security Policy (CSP) header in your Node.js Express app.

const express = require('express');
const helmet = require('helmet'); // Helmet helps set various security headers

const app = express();
const port = 3000;

// Use Helmet middleware to set security headers, including CSP
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"], // Default policy for fetching resources
    scriptSrc: ["'self'", "https://unpkg.com/some-script.js"], // Only allow scripts from self and unpkg CDN
    styleSrc: ["'self'", "https://fonts.googleapis.com"], // Only allow styles from self and Google Fonts
    imgSrc: ["'self'", "data:", "https://images.example.com"], // Allow images from self, data URIs, and example.com
    fontSrc: ["'self'", "https://fonts.gstatic.com"], // Allow fonts from self and Google Fonts
    connectSrc: ["'self'", "wss://your-websocket-server.com"], // Allow fetch/XHR from self and WebSocket server
    objectSrc: ["'none'"], // Prevent loading of <object>, <embed>, <applet> elements
    frameSrc: ["'self'", "https://www.youtube.com"], // Allow frames from self and YouTube
    formAction: ["'self'"], // Restrict URLs that can be used as the target for form submissions
    upgradeInsecureRequests: [], // Automatically rewrite HTTP URLs to HTTPS
  },
  reportOnly: false // Set to true to only report violations without blocking
}));

// Optional: Log CSP violations to a report URI (requires a backend endpoint to receive reports)
/*
app.use(helmet.contentSecurityPolicy({
  directives: {
    // ... your directives ...
    reportUri: '/csp-violation-report-endpoint',
  }
}));

app.post('/csp-violation-report-endpoint', express.json({type: 'application/csp-report'}), (req, res) => {
  console.log('CSP Violation Report:', req.body);
  res.status(204).send();
});
*/

app.get('/', (req, res) => {
  res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>CSP Demo</title>
          <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto&display=swap">
          <style>body { font-family: 'Roboto', sans-serif; }</style>
        </head>
        <body>
          <h1>Content Security Policy Example</h1>
          <p>This page uses a strict CSP. Inspect network requests and console for violations.</p>
          <script>
            // This inline script will be blocked unless 'unsafe-inline' is in scriptSrc, which is generally not recommended.
            // console.log("Inline script executed!"); 
          </script>
          <script src="https://unpkg.com/some-script.js"></script>
        </body>
        </html>
      `);
});

app.listen(port, () => {
  console.log(`Server running with CSP at http://localhost:${port}`);
});
How it works: This Node.js Express snippet shows how to implement a Content Security Policy (CSP) using the `helmet` middleware. CSP is a powerful security mechanism that mitigates XSS and other client-side injection attacks by specifying which resources (scripts, styles, images, etc.) the browser is allowed to load. Directives like `scriptSrc` and `styleSrc` restrict sources to 'self' (same origin) and explicitly whitelisted domains, blocking potentially malicious inline scripts or resources from unknown origins. `upgradeInsecureRequests` ensures all HTTP requests are automatically upgraded to HTTPS, enhancing transport security.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs