JAVASCRIPT

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

Protect your web application from XSS and data injection attacks by setting a robust Content Security Policy (CSP) header in Express.js.

const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of security middleware

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

// Use Helmet middleware to set various security headers, including CSP
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"], // Only allow resources from the same origin
    scriptSrc: ["'self'", 'https://trusted-cdn.com'], // Allow scripts from self and a trusted CDN
    styleSrc: ["'self'", "'unsafe-inline'"], // Allow styles from self and inline styles (use sparingly)
    imgSrc: ["'self'", 'data:', 'https://cdn.example.com'], // Allow images from self, data URIs, and a CDN
    fontSrc: ["'self'", 'https://fonts.gstatic.com'], // Allow fonts from self and Google Fonts
    objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
    upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
  },
}));

app.get('/', (req, res) => {
  res.send(`
    <html>
      <head>
        <title>CSP Protected Page</title>
        <style>body { font-family: sans-serif; }</style>
      </head>
      <body>
        <h1>Hello from CSP Protected Express App!</h1>
        <script>
          // This inline script will be allowed because of 'unsafe-inline' in scriptSrc (if present)
          // Or blocked if 'unsafe-inline' is not there and it's not a hash/nonce.
          console.log('Inline script executed.');
        </script>
        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="Transparent Pixel">
      </body>
    </html>
  `);
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js/Express snippet implements a Content Security Policy (CSP) using the `helmet` middleware. CSP is a powerful security feature that helps prevent Cross-Site Scripting (XSS) and other data injection attacks by whitelisting trusted sources of content. The `directives` object defines what resources (scripts, styles, images, etc.) are permitted to load, reducing the attack surface of the application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs