JAVASCRIPT

Configure Essential HTTP Security Headers with Node.js Helmet

Configure essential HTTP security headers (HSTS, X-Frame-Options, CSP) in Node.js Express with Helmet middleware. Enhance browser-side security for your web applications.

// First, install Express and Helmet: npm install express helmet

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

// Use Helmet middleware
// This adds several security headers by default:
// Content-Security-Policy, X-DNS-Prefetch-Control,
// Expect-CT, X-Frame-Options, X-Powered-By (removes),
// Strict-Transport-Security, X-Download-Options,
// X-Content-Type-Options, X-Permitted-Cross-Domain-Policies,
// Referrer-Policy
app.use(helmet());

// You can also configure specific headers
// Example: Customizing Content Security Policy (CSP)
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "https://cdn.example.com"],
      styleSrc: ["'self'", "'unsafe-inline'"], // Generally avoid 'unsafe-inline' in production
      imgSrc: ["'self'", "data:", "https://images.example.com"],
      connectSrc: ["'self'", "https://api.example.com"],
    },
  })
);

// Example: Configuring Strict-Transport-Security (HSTS)
// This tells browsers to only connect to your site using HTTPS
app.use(
  helmet.hsts({
    maxAge: 31536000, // 1 year in seconds
    includeSubDomains: true, // Apply to subdomains too
    preload: true, // Allows preloading to browser HSTS lists
  })
);

// Example: X-Frame-Options (prevents clickjacking) - Helmet sets this by default to 'DENY'
// app.use(helmet.frameguard({ action: 'deny' }));


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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running securely on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates how to easily implement crucial HTTP security headers using the `helmet` middleware for Express applications. `helmet()` without arguments applies a set of recommended default headers (like X-Frame-Options, X-Content-Type-Options, HSTS, CSP, etc.), which helps protect against common web vulnerabilities like clickjacking and XSS. The snippet also shows how to customize specific headers, such as configuring a granular Content Security Policy (CSP) to restrict resource loading or setting a long `maxAge` for Strict-Transport-Security (HSTS) to enforce HTTPS-only connections, further hardening the application's browser-side 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