JAVASCRIPT

Add Essential HTTP Security Headers for Enhanced Protection

Deploy crucial HTTP security headers like X-Content-Type-Options, Referrer-Policy, and Permissions-Policy using Express middleware to defend against common web vulnerabilities.

// Install: npm install express helmet
const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of security middlewares
const app = express();

// Use Helmet to set a variety of security headers.
// Helmet includes X-Content-Type-Options, Referrer-Policy, and many others.
app.use(helmet());

// Manually setting specific headers (if not using Helmet or for fine-tuning)
app.use((req, res, next) => {
  // X-Content-Type-Options: nosniff
  // Prevents browsers from "sniffing" a response's content type
  // away from the declared Content-Type. This can mitigate MIME-type confusion attacks.
  res.setHeader('X-Content-Type-Options', 'nosniff');

  // Referrer-Policy: no-referrer-when-downgrade (a common and secure default)
  // Controls how much referrer information is sent with requests.
  // 'no-referrer-when-downgrade' sends referrer for same-origin or HTTPS-to-HTTPS requests,
  // but not for HTTPS-to-HTTP requests.
  res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade');
  
  // Permissions-Policy (formerly Feature-Policy)
  // Allows you to selectively enable or disable browser features and APIs.
  // Example: disable camera and microphone for security on a public page.
  res.setHeader(
    'Permissions-Policy', 
    'geolocation=(self), microphone=(), camera=()' // Allow geolocation for self-origin, disable mic/cam
  );
  
  // Other headers Helmet might not set by default or you want to override:
  // X-Download-Options: noopen (for IE specific download protection)
  // res.setHeader('X-Download-Options', 'noopen');

  next();
});

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

/*
app.listen(3000, () => {
  console.log('Secure server running on port 3000');
  console.log('Check headers using browser dev tools or curl -I http://localhost:3000');
});
*/
How it works: This snippet demonstrates how to add essential HTTP security headers to a Node.js Express application, significantly enhancing its defense against various web vulnerabilities. It primarily leverages the `helmet` middleware, which automatically sets several important headers like `X-Content-Type-Options` (to prevent MIME-type sniffing) and `Referrer-Policy` (to control referrer information leakage). Additionally, it shows how to manually set or override headers like `Permissions-Policy` to control browser features (e.g., camera, microphone access) for your application, further reducing the attack surface.

Need help integrating this into your project?

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

Hire DigitalCodeLabs