JAVASCRIPT

Set Essential HTTP Security Headers with Helmet

Secure your web application by implementing crucial HTTP security headers like HSTS, X-Frame-Options, and X-Content-Type-Options using Helmet.js in Express.

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

const app = express();

// Basic Helmet setup for various security headers
app.use(helmet());

// Optionally, customize individual headers if needed
// HTTP Strict Transport Security (HSTS)
app.use(helmet.hsts({
  maxAge: 31536000, // 1 year in seconds
  includeSubDomains: true,
  preload: true
}));

// X-Frame-Options to prevent clickjacking
app.use(helmet.frameguard({ action: 'deny' }));

// X-Content-Type-Options to prevent MIME type sniffing
app.use(helmet.noSniff());

// Referrer-Policy to control referrer information leakage
app.use(helmet.referrerPolicy({ policy: 'strict-origin-when-cross-origin' }));

// Example route
app.get('/', (req, res) => {
  res.send('<h1>Security Headers Set!</h1>');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Implementing various HTTP security headers is fundamental for protecting web applications. This Node.js Express snippet leverages the `helmet` library to easily set multiple critical headers. `HSTS` (Strict-Transport-Security) forces HTTPS connections. `X-Frame-Options` prevents clickjacking attacks by controlling whether content can be embedded in an iframe. `X-Content-Type-Options` prevents MIME-type sniffing, while `Referrer-Policy` helps manage privacy by controlling what referrer information is sent with requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs