Skip to content

Commit dd00ba6

Browse files
nanotaboadaCopilot
andcommitted
fix(swagger): resolve petstore fallback caused by CSP and static file routing
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 37cb44e commit dd00ba6

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

src/app.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,12 @@ app.use(bodyParser.json());
6666
app.use(rateLimiter.generalLimiter);
6767

6868
// Swagger UI Express - https://github.com/scottie1984/swagger-ui-express
69-
app.use('/swagger', swaggerMiddleware, swaggerUi.serve, swaggerUi.setup(swaggerSpec, swaggerUiOptions));
69+
// Redirect /swagger/index.html BEFORE swaggerUi.serve, otherwise the static file
70+
// middleware serves swagger-ui-dist's own index.html (which hardcodes the petstore URL).
7071
app.get('/swagger/index.html', (_, response) => {
7172
response.redirect(301, '/swagger');
7273
});
74+
app.use('/swagger', swaggerMiddleware, swaggerUi.serve, swaggerUi.setup(undefined, swaggerUiOptions));
7375
app.get('/swagger.json', (_, response) => {
7476
response.setHeader('Content-Type', 'application/json');
7577
response.send(swaggerSpec);

src/docs/swagger.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ const validatedSwaggerSpecJSON = swaggerJSDoc(swaggerJSDocOptions);
111111
// Swagger UI Configuration
112112
const customSwaggerUiOptions: SwaggerUiOptions = {
113113
customSiteTitle: '🧪 RESTful API with Node.js and Express.js in TypeScript',
114+
// swaggerUrl overrides the window.location.origin fallback in swagger-ui-init.js;
115+
// without it, swagger-ui v5 uses the origin URL (which returns HTML, not JSON)
116+
// when both spec and url are present, causing the petstore fallback.
117+
swaggerUrl: '/swagger.json',
114118
swaggerOptions: {
115119
validatorUrl: null, // Disable external validator
116120
defaultModelsExpandDepth: -1, // Hide schemas by default

src/middlewares/swagger-middleware.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ const SWAGGER_CSP = [
55
"script-src 'self' 'unsafe-inline' cdnjs.cloudflare.com", // Allow Swagger's JS
66
"style-src 'self' 'unsafe-inline'", // Required for Swagger UI styles
77
"img-src 'self' data:", // Allow embedded image data
8+
"connect-src 'self'", // Allow Swagger UI to fetch the spec from the same origin
9+
"worker-src blob: 'self'", // Allow Swagger UI v5 to spin up its spec-parsing web worker
810
].join('; ');
911

1012
/**

0 commit comments

Comments
 (0)