JAVASCRIPT

Implementing Content Security Policy (CSP) Header in Express.js

Fortify your web application against XSS attacks and data injection by configuring a robust Content Security Policy (CSP) header in your Express.js server using the Helmet middleware.

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

// Use Helmet to set security headers, including CSP
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-scripts.com"],
    styleSrc: ["'self'", "'unsafe-inline'", "https://trusted-styles.com"],
    imgSrc: ["'self'", "data:", "https://trusted-images.com"],
    fontSrc: ["'self'", "https://fonts.gstatic.com"],
    objectSrc: ["'none'"],
    upgradeInsecureRequests: [], // Automatically rewrite HTTP requests to HTTPS
  },
}));

app.get('/', (req, res) => {
  res.send('<h1>Hello, CSP Secured World!</h1>');
});

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 added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection. It specifies which content sources are allowed to be loaded by the browser (e.g., scripts, styles, images). This snippet demonstrates how to implement a strong CSP using Helmet.js for an Express application, limiting script, style, and image sources to trusted origins and upgrading insecure HTTP requests to HTTPS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs