JAVASCRIPT

Set Secure HTTP Headers with Helmet.js in Express

Enhance your Node.js Express application's security by configuring essential 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();
const port = 3000;

// Use Helmet to set various security headers
// Helmet is a collection of 15 smaller middleware functions
app.use(helmet());

// You can also configure individual Helmet middleware if needed
// Example: Content Security Policy (CSP)
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", 'https://trusted-cdn.com'],
      styleSrc: ["'self'", 'https://trusted-cdn.com', "'unsafe-inline'"], // Be careful with 'unsafe-inline'
      imgSrc: ["'self'", 'data:'],
      connectSrc: ["'self'", 'https://api.example.com'],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [], // Automatically rewrite HTTP requests to HTTPS
    },
  })
);

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

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

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
How it works: This snippet demonstrates how to significantly improve the security of an Express.js application by setting various HTTP security headers using the `helmet` middleware. Helmet automatically configures headers like `X-Content-Type-Options`, `X-Frame-Options`, `X-XSS-Protection`, and more, mitigating common web vulnerabilities. It also shows how to configure specific headers like Content Security Policy (CSP) to control which resources (scripts, styles, images) a browser is allowed to load, preventing Cross-Site Scripting (XSS) and data injection attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs