JAVASCRIPT

Configuring Essential HTTP Security Headers in Express.js

Implement crucial HTTP security headers like X-Frame-Options, X-Content-Type-Options, and Referrer-Policy in Express.js for enhanced protection against common web vulnerabilities.

const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of security middleware

const app = express();
const port = 3000;

// Use Helmet middleware to set various security headers
app.use(helmet());

// You can also configure specific headers manually or override Helmet defaults
app.use((req, res, next) => {
  // X-Frame-Options: Prevents clickjacking by controlling if the page can be embedded in an iframe
  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');

  // X-XSS-Protection: Enables built-in XSS protection in older browsers (modern browsers use CSP)
  res.setHeader('X-XSS-Protection', '1; mode=block');

  // Referrer-Policy: Controls how much referrer information is included with requests
  res.setHeader('Referrer-Policy', 'no-referrer'); // Or 'same-origin', 'strict-origin-when-cross-origin'

  // Strict-Transport-Security (HSTS): Enforces HTTPS for future requests to the domain
  // Make sure this is only set if your site is exclusively HTTPS
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');

  next();
});

app.get('/', (req, res) => {
  res.send(`
    <html>
      <head>
        <title>Security Headers Page</title>
      </head>
      <body>
        <h1>Hello from Security Headers Protected Express App!</h1>
        <p>Check your browser's network tab to see the security headers.</p>
      </body>
    </html>
  `);
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js/Express snippet demonstrates how to implement a suite of essential HTTP security headers, often using the `helmet` middleware for convenience. Headers like `X-Frame-Options` prevent clickjacking, `X-Content-Type-Options` mitigate MIME-sniffing attacks, `X-XSS-Protection` provides browser-level XSS defense, `Referrer-Policy` manages referrer information, and `Strict-Transport-Security` enforces HTTPS, collectively bolstering the application's overall 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