req-fix-hostname
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

req-fix-hostname

NPM CI Typescript

Overwrite req.hostname with the value from another header - similar to how X-Forwarded-Host works with proxies.

Express

import express from 'express';
import { express as reqFixHostname } from 'req-fix-hostname';

const app = express();

if (process.env.X_FWD_HOST_HEADER) {
  // If X_FWD_HOST_HEADER is set & that header is present on the request, rewrite req.hostname to that value
  app.use(reqFixHostname(process.env.X_FWD_HOST_HEADER.split(',').map(s => s.trim())));
}

app.get('/', (req, res) => {
  // req.hostname will be unchangesd
  res.status(200).json('Hello, world!');
});

// Assuming X_FWD_HOST_HEADER is omitted
// req.hostname is unchanged
// => "localhost", "dev.infra.example.com"

// Assuming X_FWD_HOST_HEADER is set to: X-Forwarded-Host
// And X-Forwarded-Host = dev.example.com
// req.hostname is overwritten
// => "dev.example.com"

// Assuming X_FWD_HOST_HEADER is set to: X-Secret-Forwarded-Host
// And X-Secret-Forwarded-Host = staging.example.com
// req.hostname is overwritten
// => "staging.example.com"

// Assuming X_FWD_HOST_HEADER is set to:
//   X-Secret-Forwarded-Host, X-Forwarded-Host
// And X-Forwarded-Host = dev.example.com
// And X-Secret-Forwarded-Host = dev2.example.com
// req.hostname is overwritten as dev2 was found first
// => "dev2.example.com"

What about trust proxy?

Express behind proxies documentation

Services like AWS block developers from manipulating X-Forwarded-Host, or even the revised Forwarded header, so a new header (X-Secret-Forwarded-Host) needs to be set & used.

Readme

Keywords

none

Package Sidebar

Install

npm i req-fix-hostname

Weekly Downloads

14

Version

0.1.1

License

MIT

Unpacked Size

6.18 kB

Total Files

7

Last publish

Collaborators

  • jdrydn