← Back to all snippets
JAVASCRIPT

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

Implement a strict Content Security Policy (CSP) HTTP header in your Node.js Express application using `helmet` to mitigate XSS attacks by controlling allowed content sources.

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

const app = express();

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "https://trusted.cdn.com"],
      styleSrc: ["'self'", "'unsafe-inline'"], // Consider removing 'unsafe-inline' if possible
      imgSrc: ["'self'", "data:"],
      connectSrc: ["'self'", "api.example.com"],
      fontSrc: ["'self'"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameAncestors: ["'none'"],
      formAction: ["'self'"],
      baseUri: ["'self'"],
      reportUri: ["/csp-report-endpoint"] // Optional: for reporting violations
    }
  })
);

app.get('/', (req, res) => {
  res.send('Hello from a CSP-protected page!');
});

app.listen(3000, () => console.log('Server running with CSP on port 3000'));
How it works: This Node.js Express snippet uses the `helmet` middleware to implement a Content Security Policy (CSP) header. The `directives` object defines allowed sources for various resource types. `defaultSrc: ["'self'"]` acts as a fallback for directives not explicitly set. `scriptSrc` and `styleSrc` specify trusted origins for scripts and stylesheets. `objectSrc: ["'none'"]` disallows plugins like Flash. This policy significantly reduces the risk of Cross-Site Scripting (XSS) by preventing the execution of unauthorized code and loading of untrusted resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs