---
title: "Server routes"
description: "Write API routes with nuxt/server and validate input with valibot."
canonical_url: "https://docs.lightdrop.cloud/guides/server-routes"
---
# Server routes

> Write API routes with nuxt/server and validate input with valibot.

Routes live in `server/api/` and use the helpers from `nuxt/server`. Nothing is auto-imported on
the server, so import what you use.

```ts [server/api/todos/[id].patch.ts]
import { useDb, useValidatedBody, useValidatedParams, vh } from '@wervt/nuxt/server'
import { eq } from 'drizzle-orm'
import { createError, defineEventHandler } from 'nuxt/server'
import * as v from 'valibot'
import { todos } from '../../db/schema'

export default defineEventHandler(async (event) => {
  const { id } = await useValidatedParams(event, { id: vh.id })
  const values = await useValidatedBody(event, {
    title: v.optional(v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(200))),
    done: v.optional(v.boolean()),
  })
  const [todo] = await useDb().update(todos).set(values).where(eq(todos.id, id)).returning()
  if (!todo) throw createError({ status: 404, message: 'Todo not found' })
  return todo
})
```

## Validation

`useValidatedBody`, `useValidatedQuery` and `useValidatedParams` take a valibot schema, or a plain
object of schemas, and return typed data. Invalid input is answered with a 400 that lists the issues
per field:

```json
{
  "status": 400,
  "message": "Validation failed",
  "data": { "nested": { "id": ["Invalid digits: Received \"abc\""] } }
}
```

Query values and route params are always strings. Convert them with the
[`vh` helpers](https://docs.lightdrop.cloud/api/validation#vh): `vh.id` for ids, `vh.intAsString`, `vh.numAsString`,
`vh.boolAsString` and `vh.checkboxAsString`.

<tip>

Need to handle invalid input yourself? `useSafeValidatedBody` and friends return
`{ success, data }` or `{ success: false, issues }` instead of throwing.

</tip>

## Requests from other apps

All apps on the base domain count as one site for the browser, and the wervt login is a cookie of
that domain. A page of another app could post to your routes, and the visitor's login would come
along. That's why the runtime answers a `POST`, `PUT`, `PATCH` or `DELETE` from another app's page
with 403 before your app sees it. Requests from your own pages, from other sites (they get no
login), from the CLI, webhooks and servers pass as before.

An endpoint that other apps are meant to call from the browser, like the one of a widget they
embed, lists its path prefix in `crossApp`:

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  wervt: { crossApp: ['/api/intake/'] },
})
```

Such a route has to check the `Origin` itself and only answer the apps it knows, usually with
`handleCors` from `nuxt/server` and a list of allowed origins.

## Everything else

`nuxt/server` also has cookies (`getCookie`, `setCookie`), sessions (`useSession`), redirects,
CORS and `getRequestURL`. Prefer it over `h3` or `nitro/h3`: it is Nuxt's stable server API and
stays the same when Nitro changes underneath.

## Environment variables

API keys and other settings go through Nuxt's `runtimeConfig`: declare the key in
`nuxt.config.ts` (`runtimeConfig: { weatherApiKey: '' }`), read it with `useRuntimeConfig()` and set
it with `wervt env my-app --set NUXT_WEATHER_API_KEY=…`:

```ts [server/api/weather.get.ts]
import { createError, defineEventHandler, useRuntimeConfig } from 'nuxt/server'

export default defineEventHandler(async () => {
  const { weatherApiKey } = useRuntimeConfig()
  if (!weatherApiKey) throw createError({ status: 500, message: 'NUXT_WEATHER_API_KEY is not set' })
  return $fetch('https://api.example.com/today', { query: { key: weatherApiKey } })
})
```

[Configuration and secrets](https://docs.lightdrop.cloud/guides/configuration) explains the `NUXT_*` names, public keys and
`.env` for `nuxt dev`.


## Sitemap

See the full [sitemap](https://docs.lightdrop.cloud/sitemap.md) for all pages.
