JAVASCRIPT

Configure Essential HTTP Security Headers in Express.js

Enhance your web application's security by configuring critical HTTP headers like HSTS, CSP, X-Frame-Options, and X-Content-Type-Options in Express.js.

// Install: npm install express helmet
const express = require('express');
const helmet = require('helmet');

const app = express();

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

// Explicitly configure some headers for finer control or additional ones
app.use((req, res, next) => {
  // HSTS (HTTP Strict Transport Security) - enforce HTTPS
  // Max-Age should be high for production (e.g., 31536000 seconds = 1 year)
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');

  // X-Frame-Options - prevent clickjacking
  res.setHeader('X-Frame-Options', 'DENY');

  // X-Content-Type-Options - prevent MIME-sniffing attacks
  res.setHeader('X-Content-Type-Options', 'nosniff');

  // Referrer-Policy - control what referrer information is sent with requests
  res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade');

  // Content-Security-Policy (CSP) - mitigate XSS and data injection
  // Configure carefully based on your application's needs
  res.setHeader(
        'Content-Security-Policy',
        "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self';"
  );

  next();
});

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

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running with security headers on port ${PORT}`));
How it works: This Node.js Express snippet demonstrates how to implement essential HTTP security headers using the `helmet` middleware and custom `res.setHeader` calls. Headers like `Strict-Transport-Security` enforce HTTPS, `X-Frame-Options` prevents clickjacking, `X-Content-Type-Options` stops MIME sniffing, and `Content-Security-Policy` (CSP) significantly reduces XSS risks by controlling resource loading. Configuring these headers is crucial for modern web application security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs