JAVASCRIPT

Implementing a Content Security Policy (CSP) Header

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

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

const app = express();

// Use helmet.contentSecurityPolicy to set CSP headers
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "www.google-analytics.com"],
    styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com"],
    imgSrc: ["'self'", "data:", "www.google-analytics.com"],
    fontSrc: ["'self'", "fonts.gstatic.com"],
    connectSrc: ["'self'", "api.example.com"],
    objectSrc: ["'none'"],
    upgradeInsecureRequests: [], // Automatically upgrade HTTP to HTTPS requests
  },
}));

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

app.listen(3000, () => {
  console.log('Server running on port 3000 with CSP');
});
How it works: Content Security Policy (CSP) is an added layer of security that helps mitigate cross-site scripting (XSS) and data injection attacks. It specifies which domains the browser should consider to be valid sources of executable scripts, stylesheets, images, and other resources. This snippet demonstrates how to implement CSP in an Express.js application using the 'helmet' middleware, defining various source directives to restrict content loading to trusted origins, thereby 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