diff --git a/lib/swagger.js b/lib/swagger.js index 0edd55f..b879a18 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -114,12 +114,14 @@ function addRoute(app, uri, doc, opts) { // can't guarantee this path is either reachable or desirable if it's set // as a part of the options. // - // The simplest way around this is to reflect the value of the `Host` HTTP - // header as the `basePath`. Because we pre-build the Swagger data, we don't - // know that header at the time the data is built. + // The simplest way around this is to reflect the value of the `Host` and/or + // `X-Forwarded-Host` HTTP headers as the `basePath`. + // Because we pre-build the Swagger data, we don't know that header at + // the time the data is built. if (hasBasePath) { var headers = req.headers; - var host = headers.Host || headers.host; + // NOTE header names (keys) are always all-lowercase + var host = headers['x-forwarded-host'] || headers.host; doc.basePath = (opts.protocol || req.protocol) + '://' + host + initialPath; } diff --git a/test/swagger.test.js b/test/swagger.test.js index c6f0987..c967ad6 100644 --- a/test/swagger.test.js +++ b/test/swagger.test.js @@ -81,6 +81,18 @@ describe('swagger definition', function() { done(); }); }); + + it('respects X-Forwarded-Host header (behind a proxy)', function(done) { + var app = mountSwagger(); + getAPIDeclaration(app, 'products') + .set('X-Forwarded-Host', 'example.com') + .end(function(err, res) { + if (err) return done(err); + var baseUrl = url.parse(res.body.basePath); + expect(baseUrl.hostname).to.equal('example.com'); + done(); + }); + }); }); describe('Model definition attributes', function() {