11/* eslint-disable @typescript-eslint/ban-ts-comment */
22import { Elysia , type InternalRoute } from 'elysia'
3- import { resolve } from 'node:path' ;
43
54import { SwaggerUIRender } from './swagger'
65import { ScalarRender } from './scalar'
@@ -10,6 +9,7 @@ import { filterPaths, registerSchemaPath } from './utils'
109import type { OpenAPIV3 } from 'openapi-types'
1110import type { ReferenceConfiguration } from '@scalar/types'
1211import type { ElysiaSwaggerConfig } from './types'
12+ import { join } from 'pathe' ;
1313
1414/**
1515 * Plugin for [elysia](https://github.com/elysiajs/elysia) that auto-generate Swagger page.
@@ -61,13 +61,17 @@ export const swagger = async <Path extends string = '/swagger'>(
6161 ...documentation . info
6262 }
6363
64- const relativePath = path . startsWith ( '/' ) ? path . slice ( 1 ) : path
65-
6664 const app = new Elysia ( { name : '@elysiajs/swagger' } )
65+ const prefixedPath = join ( app . config . prefix ?? "/" , path )
66+
67+ app . get ( path , function documentation ( request ) {
68+ // External Prefix, if the app is behind a reverse proxy
69+ // For example in Traefik, the prefix is set in the header `X-Forwarded-Prefix`
70+ const extPrefix = request . headers [ "x-forwarded-prefix" ] ?? "/"
71+ const relativePath = join ( extPrefix , prefixedPath )
6772
68- app . get ( path , function documentation ( { path : reqPath } ) {
6973 const combinedSwaggerOptions = {
70- url : resolve ( reqPath , '/json' ) ,
74+ url : relativePath ,
7175 dom_id : '#swagger-ui' ,
7276 ...swaggerOptions
7377 }
@@ -84,7 +88,7 @@ export const swagger = async <Path extends string = '/swagger'>(
8488 const scalarConfiguration : ReferenceConfiguration = {
8589 spec : {
8690 ...scalarConfig . spec ,
87- url : resolve ( reqPath , '/json' )
91+ url : relativePath
8892 } ,
8993 ...scalarConfig
9094 }
@@ -105,7 +109,12 @@ export const swagger = async <Path extends string = '/swagger'>(
105109 }
106110 }
107111 )
108- } ) . get ( path === '/' ? '/json' : `${ path } /json` , function openAPISchema ( ) {
112+ } ) . get ( path === '/' ? '/json' : `${ path } /json` , function openAPISchema ( request ) {
113+ // External Prefix, if the app is behind a reverse proxy
114+ // For example in Traefik, the prefix is set in the header `X-Forwarded-Prefix`
115+ const extPrefix = request . headers [ "x-forwarded-prefix" ] ?? "/"
116+ const relativePath = join ( extPrefix , prefixedPath )
117+
109118 // @ts -expect-error Private property
110119 const routes = app . getGlobalRoutes ( ) as InternalRoute [ ]
111120
0 commit comments