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/test
routes/
hello.ts <-- /hello
nitro.config.ts

If you are using Nuxt, move the api/ and routes/ inside the server/ directory.

Simple route

// api/hello.ts
export default eventHandler(() => {
return { hello: 'world' }
})

You can now universally call this API using await $fetch('/api/hello').

Route with params

// routes/hello/[name].ts
export default eventHandler(event => `Hello ${event.context.params.name}!`)
/hello/nitro
Hello nitro!

To include the /, use [...name].ts:

// routes/hello/[...name].ts
export 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.ts
export default eventHandler(async (event) => {
const { id } = event.context.params
// TODO: fetch user by id
return `User profile!`
})
POST
// routes/users.post.ts
export default eventHandler(async event => {
const body = await readBody(event)
// TODO: Handle body and add user
return { updated: true }
})

Check out h3 JSDocs for all available utilities like readBody.

Catch all route

// routes/[...].ts
export default eventHandler(event => `Default page`)