JAVASCRIPT

Implement a Strict Content Security Policy (CSP) in Express

Configure a robust Content Security Policy (CSP) header in your Node.js Express application to significantly reduce the risk of Cross-Site Scripting (XSS) attacks by controlling allowed content sources.

const express = require('express');
const helmet = require('helmet'); // npm install helmet

const app = express();

// Use helmet.contentSecurityPolicy to set a CSP header
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"], // Only allow resources from the same origin
      scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Allow scripts from self and a specific CDN
      styleSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Allow styles from self and a specific CDN
      imgSrc: ["'self'", "data:", "https://images.example.com"], // Allow images from self, data URIs, and example.com
      connectSrc: ["'self'", "wss://api.example.com"], // Allow AJAX/WebSockets to self and API
      fontSrc: ["'self'", "https://fonts.gstatic.com"], // Allow fonts from self and Google Fonts
      objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
      baseUri: ["'self'"], // Only allow base URI from self
      formAction: ["'self'"], // Only allow form submissions to self
      frameAncestors: ["'none'"], // Prevent site from being embedded in iframes
      upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
    },
  })
);

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 Example</title>
      <style>
        body { font-family: sans-serif; }
      </style>
      <script>
        // This inline script will be allowed because of 'unsafe-inline' in scriptSrc
        console.log('Inline script executed.');
      </script>
    </head>
    <body>
      <h1>Content Security Policy Demo</h1>
      <p>This page uses a strict CSP to control resource loading.</p>
      <script src="https://trusted-cdn.com/some-script.js"></script>
      <!-- <script>alert('Malicious inline script!');</script> -->
      <!-- The above malicious script would be blocked if 'unsafe-inline' was removed -->
    </body>
    </html>
  `);
});

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running with CSP on http://localhost:${PORT}`));
How it works: This snippet demonstrates how to implement a Content Security Policy (CSP) header in an Express application using `helmet.contentSecurityPolicy`. CSP defines which content sources (scripts, styles, images, etc.) are permitted to load on your website, effectively mitigating Cross-Site Scripting (XSS) attacks. The `directives` object specifies granular rules for different resource types, such as `'self'` to allow same-origin content, or specific URLs for trusted third-party resources. `objectSrc: ["'none'"]` and `frameAncestors: ["'none'"]` add further layers of protection.

Need help integrating this into your project?

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

Hire DigitalCodeLabs