express-openapi icon indicating copy to clipboard operation
express-openapi copied to clipboard

How to document dynamic routes (app.use()) with express-openapi?

Open tit opened this issue 8 months ago • 1 comments

I’m using express-openapi to generate OpenAPI documentation for my Express.js API. However, I’m unsure how to properly document dynamic routes that are mounted using app.use(), such as:

app.use((request, response, next) => {
  if (request.path.startsWith('/_admin')) {
    return next()
  }


  const rule = Database.query('SELECT ...')

  response
    .status(rule.status)
    .send(rule.responseBody)
}

What I’ve Tried: Manually adding paths to openapi.json, but the file gets overwritten by the library. Searching the documentation for dynamic route support but found no clear guidance.

Questions: Is there a way to document these routes using JSDoc annotations? Alternatively, can I define them in a separate YAML/JSON file that express-openapi will merge?

Environment: express-openapi version: 1.1.0 Express.js version: 5.1.0

tit avatar May 27 '25 08:05 tit

If I understand what you are asking about, you should be able to use:

app.all('/_admin', openapi.path({
  description: 'Admin routes',
  tags: ['admin'],
  responses: {
    200: {
      description: 'OK',
    },
  },
}), (request, response, next) => {
  return next()
})

app.use((request, response, next) => {
  const rule = Database.query('SELECT ...')

  response
    .status(rule.status)
    .send(rule.responseBody)
})

If you want a route to be in the openapi spec, you need to use the one of the middlewares outlined in the README (ie OpenApiMiddleware.path())

Megapixel99 avatar Sep 22 '25 15:09 Megapixel99