JAVASCRIPT

Essential HTTP Security Headers for Web Applications

Implement critical HTTP security headers like `X-Content-Type-Options` and `Referrer-Policy` to mitigate MIME-sniffing and referrer leakage risks effectively.

const express = require('express');
const helmet = require('helmet'); // A suite of security middleware

const app = express();

// Use Helmet to set various security headers, including the ones below, and more.
// However, for explicit demonstration, we'll show direct setting or custom Helmet configuration.
app.use(helmet()); // Sets many headers by default including X-Content-Type-Options: nosniff

// Explicitly set X-Content-Type-Options (Helmet does this by default but shown for clarity)
app.use((req, res, next) => {
  res.setHeader('X-Content-Type-Options', 'nosniff');
  next();
});

// Configure Referrer-Policy using Helmet (or manually via res.setHeader)
app.use(helmet.referrerPolicy({ policy: 'no-referrer' }));
// Common policies include: 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url'

app.get('/', (req, res) => {
  res.send('This page is protected by essential HTTP security headers.');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates the implementation of crucial HTTP security headers in an Express.js application, often facilitated by the `helmet` middleware. `X-Content-Type-Options: nosniff` prevents browsers from "sniffing" MIME types and interpreting files as different content types (e.g., executing a user-uploaded image as a script), thus mitigating certain XSS attacks. The `Referrer-Policy` header controls how much referrer information is sent with requests, preventing the leakage of sensitive URLs to third-party sites. Together, these headers enhance client-side security and privacy.

Need help integrating this into your project?

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

Hire DigitalCodeLabs