JAVASCRIPT

Implementing Strict Content Security Policy (CSP) with Helmet.js

Implement a robust Content Security Policy (CSP) in Node.js Express applications using Helmet.js to mitigate XSS and data injection vulnerabilities.

const express = require('express');
const helmet = require('helmet');
const app = express();

// Use Helmet to set various security headers
app.use(helmet());

// Configure a strict Content Security Policy
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Be specific with sources
      styleSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"],
      imgSrc: ["'self'", "data:", "https://trusted-cdn.com"],
      fontSrc: ["'self'", "https://trusted-cdn.com"],
      objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
      upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
    },
  })
);

app.get('/', (req, res) => {
  res.send('Hello, secure web!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet shows how to implement a Content Security Policy (CSP) using the Helmet.js middleware. CSP is an HTTP security header that helps prevent XSS attacks by defining approved sources of content that the browser is allowed to load. By carefully configuring directives like `defaultSrc`, `scriptSrc`, and `styleSrc`, you can significantly reduce the attack surface of your web application, only allowing trusted domains and preventing injection of malicious scripts or assets.

Need help integrating this into your project?

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

Hire DigitalCodeLabs