Filesystem Routing
Nitro supports file-based routing for your API routes.
Handler files inside api/
and routes/
directory will be automatically mapped to unjs/h3 routes.
Due to some providers like Vercel using top-level
api/
directory as a feature, Nitro also supports routes/api/
to create API routes.Usage
api/ test.ts <-- /api/testroutes/ hello.ts <-- /hellonitro.config.ts
If you are using Nuxt, move the api/
and routes/
inside the server/
directory.
Simple route
// api/hello.tsexport default eventHandler(() => { return { hello: 'world' }})
You can now universally call this API using await $fetch('/api/hello')
.
Route with params
// routes/hello/[name].tsexport default eventHandler(event => `Hello ${event.context.params.name}!`)
/hello/nitro
Hello nitro!
To include the /
, use [...name].ts
:
// routes/hello/[...name].tsexport default eventHandler(event => `Hello ${event.context.params.name}!`)
/hello/nitro/is/hot
Hello nitro/is/hot!
Specific request method
API route with a specific HTTP request method (get, post, put, delete, options and so on).
GET
// routes/users/[id].get.tsexport default eventHandler(async (event) => { const { id } = event.context.params // TODO: fetch user by id return `User profile!`})
Check out h3 JSDocs for all available utilities like readBody
.
Catch all route
// routes/[...].tsexport default eventHandler(event => `Default page`)