JAVASCRIPT

Implementing HTTP Security Headers in Express.js

Learn to secure your Express.js application by implementing essential HTTP security headers like HSTS, CSP, X-Frame-Options, and X-Content-Type-Options using Helmet middleware.

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

const app = express();

// Use Helmet middleware to set various HTTP headers
app.use(helmet());

// Specific header configurations (Helmet default is good, but can be customized)
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted.cdn.com"],
    styleSrc: ["'self'", "'unsafe-inline'", "https://trusted.cdn.com"],
    imgSrc: ["'self'", "data:", "https://img.cdn.com"],
    connectSrc: ["'self'", "https://api.example.com"],
    fontSrc: ["'self'", "https://fonts.gstatic.com"],
    objectSrc: ["'none'"],
    frameAncestors: ["'none'"], // Prevents clickjacking by disabling embedding in iframes
    upgradeInsecureRequests: [],
  },
}));

app.use(helmet.hsts({
  maxAge: 31536000, // 1 year in seconds
  includeSubDomains: true,
  preload: true,
}));

app.use(helmet.frameguard({ action: 'deny' }));

app.use(helmet.noSniff());

app.use(helmet.referrerPolicy({ policy: 'no-referrer' }));

// Example route
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 demonstrates how to enhance an Express.js application's security by applying HTTP security headers using the `helmet` middleware. It sets up headers like Content Security Policy (CSP) to mitigate XSS attacks, HSTS (HTTP Strict Transport Security) to enforce HTTPS, X-Frame-Options to prevent clickjacking, and X-Content-Type-Options to prevent MIME-sniffing. These headers significantly reduce a web application's attack surface.

Need help integrating this into your project?

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

Hire DigitalCodeLabs