Skip to content

Server Routes

Server routes are defined in the server directory, and can be divided into server/api, server/routes, and server/middleware. Each file needs to export a default function defineEventHandler which takes an event object and can return either JSON, a promise, or use event.res.send() to return data.

tsx
// ~/server/api/hello.ts
export default defineEventHandler((event) => {
  return {
    api: 'works'
  }
})

Routes in the api subdirectory will be at a route /api, routes defined in the routes subdirectory will be accessible without /api.

You can also name files with a suffix to specify which request type hits which route. If not all methods are defined, methods without a matching handler will 404.

tsx
// ~/server/api/test.get.ts
export default defineEventHandler(() => 'Test get handler')

// ~/server/api/test.post.ts
export default defineEventHandler(() => 'Test post handler')

Dynamic server routes

These can be defined the same way we define dynamic navigation with brackets surrounding the variable in the file name. Catch all routes can be defined with a [...].ts.

tsx
// ~/server/api/[name].ts
export default defineEventHandler(event => `Hello, ${event.context.params.name}!`)

Catchall routes

tsx
// ~/server/api/[...].ts
export default defineEventHandler(event => `Default handler!`)

Getting Data from Request

tsx
// Request body, ONLY FOR POST REQUESTS
export default defineEventHandler(async (event) => {
    const body = await readBody(event)
    return { body }
})

// Query params
export default defineEventHandler((event) => {
  const query = getQuery(event)
  return { a: query.param1, b: query.param2 }
})

// Access runtime config
export default defineEventHandler((event) => {
  const config = useRuntimeConfig()
  return { key: config.KEY }
})

// Accessing cookies
export default defineEventHandler((event) => {
  const cookies = parseCookies(event)
  return { cookies }
})

Response status codes

tsx
export default defineEventHandler((event) => {
  throw createError({
    statusCode: 400,
    statusMessage: "Something went wrong!"
  })
})

export default defineEventHandler((event) => {
  setResponseStatus(event, 202);
})