Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add function forms of the host and protocol options #45

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

rossipedia
Copy link

👋 Not sure if this is something you'd find useful, but IMO limiting the construction of request.url to only derive from either the Host header or a static host option (and similarly for protocol) is a bit too restrictive for reverse proxy setups.

Granted, you could easily just do the work directly on request.url that's passed to the handler, but I think being able to specify functions for those options would be the least friction option for servers running behind something like HAProxy or Nginx for HTTPS termination (we actually have multiple reverse proxies in play, so the Host header that comes along isn't necessarily the one that was sent by the user's browser).

From the additions to README.md:

Alternatively the host and protocol can be derived from the request headers using the function forms of the host and protocol options (useful when running your server behind a reverse proxy). If the function provided returns
a falsy value, the default behavior is used as a fallback.

import * as assert from 'node:assert/strict';
import * as http from 'node:http';
import { createRequestListener } from '@mjackson/node-fetch-server';

function handler(request: Request) {
  // This is now true
  assert.equal(
    new URL(request.url).host,
    request.headers.get('x-forwarded-host'),
  );
  return new Response('Hello, world!');
}

let server = http.createServer(
  createRequestListener(handler, {
    host: (headers) => headers.get('x-forwarded-host'),
    protocol: (headers) => (headers.get('x-forwarded-proto') ?? 'http') + ':',
  }),
);

server.listen(3000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant