1
1
/* eslint-disable @typescript-eslint/ban-ts-comment */
2
2
import { Elysia , type InternalRoute } from 'elysia'
3
- import { resolve } from 'node:path' ;
4
3
5
4
import { SwaggerUIRender } from './swagger'
6
5
import { ScalarRender } from './scalar'
@@ -10,6 +9,7 @@ import { filterPaths, registerSchemaPath } from './utils'
10
9
import type { OpenAPIV3 } from 'openapi-types'
11
10
import type { ReferenceConfiguration } from '@scalar/types'
12
11
import type { ElysiaSwaggerConfig } from './types'
12
+ import { join } from 'pathe' ;
13
13
14
14
/**
15
15
* 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'>(
61
61
...documentation . info
62
62
}
63
63
64
- const relativePath = path . startsWith ( '/' ) ? path . slice ( 1 ) : path
65
-
66
64
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 )
67
72
68
- app . get ( path , function documentation ( { path : reqPath } ) {
69
73
const combinedSwaggerOptions = {
70
- url : resolve ( reqPath , '/json' ) ,
74
+ url : relativePath ,
71
75
dom_id : '#swagger-ui' ,
72
76
...swaggerOptions
73
77
}
@@ -84,7 +88,7 @@ export const swagger = async <Path extends string = '/swagger'>(
84
88
const scalarConfiguration : ReferenceConfiguration = {
85
89
spec : {
86
90
...scalarConfig . spec ,
87
- url : resolve ( reqPath , '/json' )
91
+ url : relativePath
88
92
} ,
89
93
...scalarConfig
90
94
}
@@ -105,7 +109,12 @@ export const swagger = async <Path extends string = '/swagger'>(
105
109
}
106
110
}
107
111
)
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
+
109
118
// @ts -expect-error Private property
110
119
const routes = app . getGlobalRoutes ( ) as InternalRoute [ ]
111
120
0 commit comments