JAVASCRIPT

Implement a Robust Content Security Policy in Express

Strengthen web app security against XSS by implementing a Content Security Policy (CSP) using `helmet` middleware in Express.js, controlling allowed content sources.

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

const app = express();

// Use Helmet to set security-related HTTP headers
app.use(helmet());

// Customize CSP to allow only trusted sources
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"], // Only allow resources from the same origin by default
      scriptSrc: ["'self'", 'https://trusted-cdn.com'], // Allow scripts from self and a trusted CDN
      styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'], // Allow inline styles for simplicity, but avoid if possible
      imgSrc: ["'self'", 'data:', 'https://cdn.example.com'], // Allow images from self, data URIs, and a trusted image CDN
      fontSrc: ["'self'", 'https://fonts.gstatic.com'], // Allow fonts from self and Google Fonts CDN
      objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
      baseUri: ["'self'"], // Disallow arbitrary <base> tags
      formAction: ["'self'"], // Only allow forms to submit to same origin
      frameAncestors: ["'none'"], // Prevent clickjacking by disallowing embedding in iframes
      upgradeInsecureRequests: [], // Automatically upgrade insecure HTTP requests to HTTPS
    },
  })
);

app.get('/', (req, res) => {
  res.send('<h1>Hello, secure web!</h1><script>alert("This script is blocked by CSP!");</script>');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Open http://localhost:3000 in your browser and check console for CSP violations.');
});
How it works: This snippet demonstrates how to implement a Content Security Policy (CSP) in an Express.js application using the `helmet` middleware. CSP is a powerful security layer that helps mitigate Cross-Site Scripting (XSS) and data injection attacks by specifying allowed sources for various content types (scripts, styles, images, etc.). The `directives` object defines granular rules, such as `scriptSrc` to control script execution and `defaultSrc` for a baseline policy. `frameAncestors: ["'none'"]` specifically prevents clickjacking. This setup significantly reduces the attack surface of your application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs