nitro icon indicating copy to clipboard operation
nitro copied to clipboard

Expose handlers list through the useNitroApp

Open artmizu opened this issue 9 months ago • 2 comments

Describe the feature

Hello, and thank you for your continued work on the open-source ecosystem — it's incredibly appreciated!

I’d like to propose exposing an additional API through useNitroApp that would allow access to the list of route handlers generated from the filesystem. This feature can be particularly useful when such metadata is needed on the client side.

For context, I received a request related to this functionality in one of my Nuxt modules. However, I couldn't find a clean way to implement it without extending Nitro itself.

Would you be open to this idea? I’ve created a draft PR to demonstrate the concept. If the approach makes sense, I’d be happy to clean it up — removing unnecessary playground files, adding proper test cases, and aligning with project conventions.

Alternatively, it might make more sense to implement this in the H3 layer. I know app.stack exists there, but it currently returns an empty array. If it’s more appropriate, I can explore that direction as well and expose the API via H3 instead.

Looking forward to hearing your thoughts!

Additional information

  • [x] Would you be willing to help implement this feature?

artmizu avatar Apr 11 '25 13:04 artmizu

Thanks for opening the discussion (and for the draft PR).

I understand there are use cases in which we need to have access to available handlers/route patterns.

We cannot export this meta from nitroApp instance (#3307) because it makes it non-tree-shakable when this meta is not usable. Also, h3.stack is an internal (it is removed from h3 v2).

I think we also need to export a subset (serializable) of the patterns (array of { route, method } without action handler function).

We can export this info using a module as alternative, it can access nitro.scannedhandlers + nitro.options.handlers to construct this array and make it available to runtime using a virtual template.

pi0 avatar Apr 13 '25 11:04 pi0

Also, checking https://github.com/artmizu/nuxt-prometheus/issues/48, actually you can already access to the runtime matched route pattern.

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('beforeResponse', (event, { body }) => {
    console.log(event.method, event.path, event.context.matchedRoute);
  });
});
GET /test/foo {
  path: '/test/:id',
  handlers: {
    all: [Function (anonymous)] {
      __is_handler__: true,
      __resolve__: [Function: resolveHandler]
    }
  },
  params: { id: 'foo' }
}

https://stackblitz.com/edit/unjs-nitro-starter-zi4ctfqs?file=nitro.config.ts,package.json,server%2Fplugins%2Flog.ts,server%2Froutes%2Findex.ts&title=Nitro%20Starter

pi0 avatar Apr 13 '25 11:04 pi0