JAVASCRIPT

Implement a Strict Content Security Policy (CSP) Header

Enhance web application security by implementing a Content Security Policy (CSP) header in Node.js with Express, mitigating XSS and data injection attacks.

const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers

const app = express();

// Use Helmet to set security headers, including CSP
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"], // Only allow resources from the same origin
    scriptSrc: ["'self'", "https://trusted-cdn.com"], // Allow scripts from self and a specific CDN
    styleSrc: ["'self'", "'unsafe-inline'"], // Allow styles from self and inline styles (use with caution)
    imgSrc: ["'self'", "data:", "https://img.example.com"], // Allow images from self, data URIs, and a specific domain
    connectSrc: ["'self'", "https://api.example.com"], // Allow API calls to self and a specific API domain
    objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
    frameSrc: ["'self'", "https://trusted-iframe.com"], // Allow iframes from self and a trusted source
    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 shows how to implement a Content Security Policy (CSP) header in an Express.js application using the `helmet` middleware. CSP is a powerful security mechanism that helps mitigate Cross-Site Scripting (XSS) and other data injection attacks by specifying which sources of content (scripts, stylesheets, images, etc.) are allowed to be loaded by the browser. The example sets strict directives, allowing resources only from trusted origins, thus significantly reducing attack vectors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs