API routes with route params not having types
I noticed my API routes only have typings if they do not contain a route param. Is this expected behavior? Is there a way to fix / improve it in the project? The docs don't say anything about it.
Example:
2 Replies
Hi @Tackleberry. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
This is indeed an interesting observation about API routes with route parameters in Nuxt. Let's explore this based on the available information.
According to the Nuxt documentation on Typed API Routes (https://nuxt.com/docs/guide/concepts/server-engine#typed-api-routes), Nitro (Nuxt's server engine) should generate typings for API routes as long as you are returning a value instead of using
res.end()
to send a response. However, the documentation doesn't specifically address the behavior with route parameters.
The behavior you're experiencing, where routes with parameters are not typed, isn't explicitly mentioned as expected behavior in the documentation. However, it's possible that this is a limitation or an area where the type inference system struggles.
To potentially improve this situation, you could try the following approaches:
1. Use defineEventHandler
with explicit typing:
2. Utilize getValidatedRouterParams
for runtime and type safety, as suggested in the Nuxt server directory documentation (https://nuxt.com/docs/guide/directory-structure/server#recipes):
3. Consider enabling the experimental typedPages
feature in your nuxt.config.ts
, which might improve type inference for routes:
As mentioned in the Nuxt experimental features documentation (https://nuxt.com/docs/guide/going-further/experimental-features#typedpages), this feature enables a new experimental typed router using unplugin-vue-router
.
It's worth noting that Nuxt's typing system is continuously evolving, and this behavior might be improved in future versions. If you find that these solutions don't fully address the issue, you might want to consider opening an issue on the Nuxt GitHub repository to bring attention to this specific use case.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@615642942777851938> Kapa.ai is still learning and improving, please let me know how I did by reacting below.