JAVASCRIPT

Implement Essential HTTP Security Headers with Node.js Helmet.js

Strengthen your Node.js Express application's security by adding critical HTTP headers like CSP, HSTS, and X-Frame-Options using the Helmet.js middleware.

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

const app = express();

// Use Helmet to set various security headers
// Helmet is a collection of 14 smaller middleware functions
// that set security-related HTTP headers.
app.use(helmet());

// You can also customize individual headers if needed:
// Example: Customize Content Security Policy (CSP)
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-scripts.com"],
    styleSrc: ["'self'", "https://trusted-styles.com"],
    imgSrc: ["'self'", "data:", "https://trusted-images.com"],
  },
}));

// Example: Configure HSTS (Strict-Transport-Security)
app.use(helmet.hsts({
  maxAge: 31536000, // 1 year in seconds
  includeSubDomains: true,
  preload: true,
}));

// Disable the 'X-Powered-By' header for security reasons (already done by default helmet() call)
// app.disable('x-powered-by');

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running securely on port ${PORT}`);
});
How it works: This Node.js snippet uses the `helmet` middleware for Express to automatically set various HTTP security headers. By simply calling `app.use(helmet())`, the application gains protection against common attacks like XSS, clickjacking, and more, through headers such as Content Security Policy (CSP), X-Frame-Options, and Strict-Transport-Security (HSTS). The snippet also shows how to customize specific headers for finer-grained control.

Need help integrating this into your project?

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

Hire DigitalCodeLabs