Swagger UI server URL resolution failure behind reverse proxies
0 reputation · 07 Jan 2023, 14:15 UTC
0 reputation · 07 Jan 2023, 14:15 UTC
The OpenAPI specification utilizes a servers array to define the base URLs for API requests. While relative paths often resolve correctly in local development environments, the behavior changes when the Swagger UI is deployed to production behind a reverse proxy or API Gateway.
When the UI is hosted on a different domain or subdirectory than the backend API, the browser-side resolution of relative paths may result in incorrect request routing or CORS violations. There is uncertainty regarding how different versions of Swagger UI handle the prepending of base paths when the servers object is dynamically populated at runtime versus being hardcoded in the specification file.
What is the documented behavior for resolving relative server paths when the UI is served from a separate origin than the API? How does the servers configuration interact with reverse proxy headers to ensure consistent request routing across multiple environments?
33275 reputation · 07 Jan 2023, 20:39 UTC
Swagger UI treats relative URLs in the servers array as relative to the browser window’s origin (window.location.origin). It does not consult reverse‑proxy headers such as X-Forwarded-Host or X-Forwarded-Proto; those are only meaningful to the backend server.
servers array is read from the OpenAPI document (JSON/YAML) that Swagger UI loads./api), the UI prepends window.location.origin to form the absolute request URL.When the UI is served from a different origin than the API, a relative server entry resolves to the UI’s origin, causing requests to be sent to the wrong host (often resulting in 404 or CORS errors). The UI has no way to infer the external host that the reverse proxy presents to clients.
swagger.json (or the OpenAPI endpoint) and verify the servers array content.https://api.example.com).servers array is populated from an environment variable or from request headers (e.g., using X-Forwarded-Host on the server side).Is the OpenAPI specification (swagger.json) being served from the same origin as the Swagger UI, or is it proxied through the same reverse‑proxy layer? Knowing this determines whether you need to adjust the UI’s base URL or modify the backend’s dynamic server generation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.