JAVASCRIPT

Implement Content Security Policy (CSP) Header

Learn to implement a Content Security Policy (CSP) header to mitigate Cross-Site Scripting (XSS) and other code injection attacks by restricting resource loading.

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

app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"],
    styleSrc: ["'self'", "https://fonts.googleapis.com"],
    imgSrc: ["'self'", "data:", "https://images.example.com"],
    connectSrc: ["'self'", "https://api.example.com"],
    fontSrc: ["'self'", "https://fonts.gstatic.com"],
    objectSrc: ["'none'"],
    mediaSrc: ["'self'"],
    frameSrc: ["'none'"],
    workerSrc: ["'self'"],
    formAction: ["'self'"],
    upgradeInsecureRequests: [], // Automatically upgrade HTTP to HTTPS
  },
}));

// Your other routes and middleware
app.get('/', (req, res) => {
  res.send('Hello, secure web!');
});

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 the Helmet middleware for Express.js. CSP is a powerful security feature that helps prevent XSS attacks by defining which resources (scripts, styles, images, etc.) the browser is allowed to load. Directives like `defaultSrc`, `scriptSrc`, and `styleSrc` specify trusted sources. `'self'` allows resources from the same origin, while specific domains can be whitelisted. `'unsafe-inline'` should be used sparingly and only when necessary, as it diminishes CSP's security benefits.

Need help integrating this into your project?

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

Hire DigitalCodeLabs