Optimize middleware in express when using swagger-ui-express

Hi campers,
I am using swagger-ui-express to generate an API documentation. Below is how I have implemented the /documentation endpoint. I am dynamically mutating the JSON swaggerDocument as described in the doc under “Modify swagger file on the fly before load” section.

const swaggerDocument = require("./swagger.json");
const swaggerOptions = { explorer: true, customSiteTitle: "Quiz API" };

app.use("/documentation", async (req, res, next) => {
    // Fetch data from the database and mutate swaggerDocument here
    console.log("Middleware has been called");
    req.swaggerDoc = swaggerDocument; 
  }, swaggerUi.serve, swaggerUi.setup(undefined, swaggerOptions));

Every time I hit the /documentation endpoint, the middleware above is invoked 6 times. I am not sure if there is something I am doing wrong or that is how it is supposed to be. I just want it to be invoked once since I am reading from the DB. I know I can also read from the database once by doing something like:

let updatedSwaggerDoc = false;
app.use("/documentation", async (req, res, next) => {
      // Fetch from database and update swaggerDoc
       req.swaggerDoc = swaggerDocument; 
       updatedSwaggerDoc = true;
  }, swaggerUi.serve, swaggerUi.setup(undefined, swaggerOptions));

I am wondering why the middleware is invoked 6 times. I have failed to find an answer in the documentation.

So I tried your code and it seems that swagger does make 6 requests:


Maybe you could filter by path. Say:

if (req.path !== '/') return next()
1 Like

So you think it is swaggerUI making the extra requests. I thought probably there was something wrong with my configuration. I don’t understand the logic behind path filtering.

Swagger needs those assets to render the docs page, which are being served by your app.

1 Like

Well it’s pretty obvious it does.

If it is the initial request (to the root of the endpoint), then run middleware. If it’s not, then don’t do anything.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.