Nitro URL template
Hi all
Is there a way to fetch the URL template from within a nitro event handler?
For example, say I have some file
/api/book/[id].get.ts
.
If I fetch /api/book/123
, how can some middleware display to me that it was this dynamic route that was hit.
The underlying reason is I want to log how often each endpoint is used. Part of this would be seeing each individual URL, which is straightforward. However I'd like to leverage the dynamic pattern too, so I can store that /api/book/123
uses the same handler as /api/book/456
.
Thanks in advance if anyone knows3 Replies
Hi @jamzy. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes, you can access the URL template from within a Nitro event handler. When working with Nuxt's server routes, you can use the event object to get information about the current request.
To access the route pattern that was matched (like
/api/book/[id]
), you can use the Nitro event object. While the knowledge sources don't provide a direct example for your specific use case, you can implement this using Nitro's hooks system.
Here's how you could approach this:
1. Create a server plugin to log route patterns:
This plugin will be automatically registered by Nuxt since it's in the server/plugins
directory.
For more advanced usage, you could also create a custom middleware:
The Nitro hooks system provides several hooks you can use for this purpose, as documented in the Nitro App Hooks documentation.
If you need more control, you could also create a custom module that adds a server plugin using the Nuxt Kit API's addServerPlugin
function as shown in the Kit Nitro documentation.
Note that the exact property names might vary depending on your Nuxt/Nitro version, so you might need to inspect the event object structure in your specific environment.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@340181914361004052> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
These options don't seem to exist for me on nitroApp