← Back to all snippets
JAVASCRIPT

Implementing a Strict Content Security Policy (CSP)

Learn to implement a robust Content Security Policy (CSP) header in your Express.js application to mitigate Cross-Site Scripting (XSS) and other code injection attacks.

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

app.use((req, res, next) => {
  // Define your CSP directives
  const cspDirectives = [
    "default-src 'self'",
    "script-src 'self' 'unsafe-inline' https://cdn.example.com", // Adjust for your scripts
    "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com", // Adjust for your styles
    "img-src 'self' data: https://img.example.com", // Adjust for your images
    "font-src 'self' https://fonts.gstatic.com", // Adjust for your fonts
    "connect-src 'self' ws://localhost:3000", // Adjust for API calls, WebSockets
    "object-src 'none'", // Block Flash and other plugins
    "frame-ancestors 'none'", // Prevent clickjacking
    "base-uri 'self'",
    "form-action 'self'",
    "upgrade-insecure-requests" // Automatically upgrade HTTP to HTTPS requests
  ];

  res.setHeader('Content-Security-Policy', cspDirectives.join('; '));
  next();
});

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to set a strong `Content-Security-Policy` header in an Express.js application. CSP helps prevent Cross-Site Scripting (XSS) and other data injection attacks by restricting the sources from which content can be loaded. It defines various directives (e.g., `script-src`, `style-src`, `img-src`) to whitelist trusted origins for different types of resources, enhancing the application's 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