JAVASCRIPT

Implement a Strict Content Security Policy (CSP)

Fortify web applications against XSS and data injection by implementing a strict Content Security Policy (CSP) with recommended directives for enhanced security.

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

const app = express();

// Configure CSP
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'" /* Consider removing 'unsafe-inline' in production and using nonces/hashes */, 'https://trusted-cdn.com'],
      styleSrc: ["'self'", "'unsafe-inline'"], // For inline styles, consider moving to external stylesheets or using nonces/hashes
      imgSrc: ["'self'", 'data:', 'https://cdn.example.com'],
      connectSrc: ["'self'", 'https://api.example.com'],
      fontSrc: ["'self'", 'https://fonts.gstatic.com'],
      objectSrc: ["'none'"],
      frameAncestors: ["'none'"],
      upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
    },
  })
);

// Other middleware and routes
app.get('/', (req, res) => {
  res.send('Hello Secure World!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Content Security Policy (CSP) is an HTTP security header that helps prevent cross-site scripting (XSS) and other code injection attacks by specifying which resources the user agent is allowed to load. This Node.js (Express) snippet uses the `helmet` middleware to set a strict CSP. It defines allowed sources for scripts, styles, images, and other content, effectively whitelisting trusted origins. 'default-src' provides a fallback for many directives. 'object-src' and 'frame-ancestors' set to 'none' are crucial for preventing certain types of attacks like clickjacking and embedding malicious content. The `upgradeInsecureRequests` directive automatically converts all HTTP URLs to HTTPS within the document.

Need help integrating this into your project?

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

Hire DigitalCodeLabs