JAVASCRIPT

Implementing a Robust Content Security Policy (CSP)

Enhance web application security by implementing a Content Security Policy (CSP) to prevent XSS and injection attacks, controlling resource loading.

const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of 14 middleware functions that help set various HTTP headers for security

const app = express();

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

// Configure CSP specifically. Helmet's default CSP might be too strict or not specific enough.
// It's often better to configure it explicitly.
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"], // Only allow resources from the same origin
      scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Allow self, inline scripts (if necessary), and a specific CDN
      styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
      imgSrc: ["'self'", "data:", "https://images.example.com"],
      fontSrc: ["'self'", "https://fonts.gstatic.com"],
      objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
      baseUri: ["'self'"],
      formAction: ["'self'"], // Only allow forms to submit to the same origin
      frameAncestors: ["'none'"], // Prevent clickjacking by disallowing embedding in iframes
      upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
    },
  })
);

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: This snippet demonstrates how to implement a Content Security Policy (CSP) using Node.js with Express and the `helmet` middleware. CSP is a powerful security layer that helps prevent Cross-Site Scripting (XSS) and other code injection attacks by specifying which content sources are allowed to load and execute on a web page. The `directives` object defines granular rules for different resource types, such as scripts, styles, images, and forms, restricting them to trusted origins and enhancing the application's overall security posture.

Need help integrating this into your project?

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

Hire DigitalCodeLabs