← Back to all snippets
JAVASCRIPT

Implement Essential HTTP Security Headers

Protect web applications from common attacks like clickjacking and XSS by configuring fundamental HTTP security headers in Node.js Express. Enhance overall application security.

const express = require('express');
const helmet = require('helmet'); // Recommended for production
const app = express();

// Using helmet for a robust set of security headers
app.use(helmet());

// Custom headers if you don't use helmet or need specific overrides
app.use((req, res, next) => {
  // HSTS: Enforces secure (HTTPS) connections to the server
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
  // X-Frame-Options: Prevents clickjacking by denying embedded content
  res.setHeader('X-Frame-Options', 'DENY');
  // X-Content-Type-Options: Prevents browsers from MIME-sniffing a response away from the declared content-type
  res.setHeader('X-Content-Type-Options', 'nosniff');
  // Referrer-Policy: Controls how much referrer information is sent with requests
  res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade');
  // X-XSS-Protection: Enables built-in XSS protection in older browsers
  res.setHeader('X-XSS-Protection', '1; mode=block');
  next();
});

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

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
How it works: This snippet demonstrates how to implement crucial HTTP security headers in an Express.js application. Headers like `Strict-Transport-Security` enforce HTTPS, `X-Frame-Options` prevents clickjacking, and `X-Content-Type-Options` mitigates MIME-sniffing attacks. While manually setting headers is shown, using the `helmet` middleware is highly recommended in production as it provides a robust collection of security headers with minimal configuration, significantly improving your application's security posture against common web vulnerabilities.

Need help integrating this into your project?

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

Hire DigitalCodeLabs