
# Server Utilities

> A reference of everything you can import from `nitro` and its subpaths in your server code.

Nitro has **no auto-imports**: every utility must be explicitly imported from the main `nitro` entry or one of its subpaths. This page maps each export to its import path.

## Quick reference

| What you want to do | Import |
| --- | --- |
| Define an event handler | `import { defineHandler } from "nitro"`{lang=ts} |
| Define a middleware | `import { defineMiddleware } from "nitro"`{lang=ts} |
| Throw an HTTP error | `import { HTTPError } from "nitro"`{lang=ts} |
| Read the body, query, cookies, ... | `import { readBody, getQuery } from "nitro/h3"`{lang=ts} |
| Call your own routes internally | `import { serverFetch } from "nitro"`{lang=ts} |
| Handle WebSocket connections | `import { defineWebSocketHandler } from "nitro"`{lang=ts} |
| Add a runtime plugin | `import { definePlugin } from "nitro"`{lang=ts} |
| Customize the error response | `import { defineErrorHandler } from "nitro"`{lang=ts} |
| Cache a handler or function | `import { defineCachedHandler, defineCachedFunction } from "nitro/cache"`{lang=ts} |
| Read/write key-value storage | `import { useKV } from "nitro/kv"`{lang=ts} |
| Query a SQL database | `import { useDatabase } from "nitro/database"`{lang=ts} |
| Access runtime config | `import { useRuntimeConfig } from "nitro/runtime-config"`{lang=ts} |
| Define and run tasks | `import { defineTask, runTask } from "nitro/task"`{lang=ts} |
| Access the app instance and hooks | `import { useNitroApp, useNitroHooks } from "nitro/app"`{lang=ts} |
| Configure Nitro (`nitro.config.ts`) | `import { defineConfig } from "nitro"`{lang=ts} |
| Use Nitro as a Vite plugin | `import { nitro } from "nitro/vite"`{lang=ts} |

## `nitro`

The main entry contains everything you need for day-to-day route handlers.

| Export | Description |
| --- | --- |
| `defineHandler` | Define an event handler for a [route or middleware file](/docs/routing). |
| `defineMiddleware` | Define a [middleware](/docs/routing#middleware) that runs before route handlers. |
| `defineWebSocketHandler` | Define a [WebSocket handler](/docs/websocket) for a route file. |
| `definePlugin` | Define a [runtime plugin](/docs/plugins) that runs on server startup. |
| `defineErrorHandler` | Define a custom [error handler](/config#errorhandler) to replace the built-in error page. |
| `defineConfig` | Define Nitro [configuration](/docs/configuration) (used in `nitro.config.ts`, not in runtime code). |
| `defineRouteMeta` | Attach route metadata such as [OpenAPI specs](/docs/openapi) (build-time macro). |
| `HTTPError` | Throw HTTP errors with a status code: `throw new HTTPError("Not found", { status: 404 })`{lang=ts}. |
| `HTTPResponse` | Return a body with a custom status and headers from a handler. |
| `html` | Tagged template literal returning an HTML response (`text/html` content type). |
| `serverFetch` | Call your own routes internally, without a network round-trip. |
| `fetch` | Like global `fetch`, but paths starting with `/` are routed to your own server. |

Commonly used types are also exported: `H3Event`, `EventHandlerRequest`, and `EventHandlerWithFetch`.

```ts [server/routes/hello.ts]
import { defineHandler, HTTPError } from "nitro";

export default defineHandler((event) => {
  const name = event.url.searchParams.get("name");
  if (!name) {
    throw new HTTPError("Missing name", { status: 400 });
  }
  return { hello: name };
});
```

### Internal fetch

`serverFetch` calls a route of your own app directly: the request goes through the Nitro app (route rules, middleware, plugins) without touching the network:

```ts [server/routes/summary.ts]
import { defineHandler, serverFetch } from "nitro";

export default defineHandler(async () => {
  const res = await serverFetch("/api/stats"); // returns a web Response
  return { stats: await res.json() };
});
```

The `fetch` export is a universal variant: absolute paths (starting with `/`) are handled internally via `serverFetch`, everything else falls back to global `fetch`:

```ts
import { fetch } from "nitro";

await fetch("/api/hello"); // handled by your own server
await fetch("https://example.com"); // regular network fetch
```

### Error handler

Point the [`errorHandler` config](/config#errorhandler) to a file that exports a custom error handler:

```ts [error.ts]
import { defineErrorHandler } from "nitro";

export default defineErrorHandler((error, event) => {
  return new Response(`[custom error] ${error.message}`, {
    status: error.status,
    headers: { "Content-Type": "text/plain" },
  });
});
```

### Runtime plugins

Plugins run once on server startup and can hook into the [runtime lifecycle](/docs/lifecycle):

```ts [server/plugins/log.ts]
import { definePlugin } from "nitro";

export default definePlugin((nitroApp) => {
  nitroApp.hooks.hook("request", (event) => {
    console.log("request:", event.url.pathname);
  });
});
```

See the [plugins guide](/docs/plugins) for more.

## `nitro/h3`

Re-exports all [H3 v2](https://h3.dev) utilities: `readBody`, `getQuery`, `getCookie`, `setCookie`, `proxy`, `redirect`, and many more.

```ts [server/routes/form.post.ts]
import { defineHandler } from "nitro";
import { readBody, getCookie } from "nitro/h3";

export default defineHandler(async (event) => {
  const body = await readBody(event);
  const session = getCookie(event, "session");
  return { body, session };
});
```

::note
See the [H3 utilities documentation](https://h3.dev/utils) for the full list.
::

## `nitro/cache`

| Export | Description |
| --- | --- |
| `defineCachedHandler` | Wrap an event handler with caching. |
| `defineCachedFunction` | Cache the result of any (async) function. |

```ts
import { defineCachedHandler } from "nitro/cache";

export default defineCachedHandler(() => `Generated at ${new Date().toISOString()}`, {
  maxAge: 60,
});
```

See the [cache guide](/docs/cache) for options, cache keys, and invalidation.

## `nitro/kv`

| Export | Description |
| --- | --- |
| `useKV` | Access the key-value [storage layer](/docs/storage), optionally scoped to a base (e.g. `useKV("data")`{lang=ts}). |

```ts
import { useKV } from "nitro/kv";

await useKV("data").set("visits", 42);
```

See the [KV storage guide](/docs/storage) for mountpoints and drivers.

::note
`useStorage` from `nitro/storage` still works as a deprecated alias of `useKV`.
::

## `nitro/database`

| Export | Description |
| --- | --- |
| `useDatabase` | Access a configured SQL [database](/docs/database) connection (default: `useDatabase()`{lang=ts}, named: `useDatabase("users")`{lang=ts}). |

```ts
import { useDatabase } from "nitro/database";

const db = useDatabase();
const { rows } = await db.sql`SELECT * FROM users`;
```

See the [database guide](/docs/database) for connectors and configuration.

## `nitro/runtime-config`

| Export | Description |
| --- | --- |
| `useRuntimeConfig` | Access [runtime configuration](/docs/configuration#runtime-configuration), overridable with `NITRO_*` environment variables. |

```ts
import { useRuntimeConfig } from "nitro/runtime-config";

const { apiToken } = useRuntimeConfig();
```

## `nitro/task`

| Export | Description |
| --- | --- |
| `defineTask` | Define a [task](/docs/tasks) in a `server/tasks/` file. |
| `runTask` | Run a task by name from anywhere in your server code. |

```ts
import { runTask } from "nitro/task";

const { result } = await runTask("db:migrate", { payload: { force: true } });
```

See the [tasks guide](/docs/tasks). Tasks are experimental and require the `experimental.tasks` flag.

## `nitro/app`

Lower-level access to the running Nitro app.

| Export | Description |
| --- | --- |
| `useNitroApp` | Access the current [Nitro app instance](/docs/lifecycle) (`fetch`, `hooks`, ...). |
| `useNitroHooks` | Access the [runtime hooks](/docs/plugins#nitro-runtime-hooks) instance to register hooks outside of plugins. |
| `getRouteRules` | Get the resolved [route rules](/docs/routing#route-rules) for a method and pathname: `getRouteRules("GET", "/blog/post")`{lang=ts}. |
| `serverFetch`, `fetch` | Same as the [main entry exports](#internal-fetch). |

```ts
import { useNitroHooks } from "nitro/app";

useNitroHooks().hook("error", (error) => {
  console.error(error);
});
```

## `nitro/context`

| Export | Description |
| --- | --- |
| `useRequest` | Access the current request from anywhere within the request lifecycle, without passing `event` around. |

```ts
import { useRequest } from "nitro/context";

const request = useRequest();
```

::warning
`useRequest` is experimental: it requires the `experimental.asyncContext: true`{lang=ts} config flag and only works on runtimes with `AsyncLocalStorage` support (Node.js and compatible runtimes).
::

## `nitro/config`

| Export | Description |
| --- | --- |
| `defineConfig` | Same as the `defineConfig` export from the main `nitro` entry (also aliased as `defineNitroConfig`). |

Prefer importing `defineConfig` from `"nitro"` directly.

## `nitro/types`

Type-only entry with all public Nitro types, including `NitroConfig`, `Nitro`, `NitroApp`, `NitroAppPlugin`, `NitroErrorHandler`, `NitroRuntimeConfig`, `NitroRuntimeHooks`, and `Task`.

```ts
import type { NitroRuntimeConfig } from "nitro/types";
```

## `nitro/vite`

| Export | Description |
| --- | --- |
| `nitro` | The Nitro [Vite plugin](/docs/vite). |

```ts [vite.config.ts]
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";

export default defineConfig({
  plugins: [nitro()],
});
```

The `NitroPluginConfig` and `ViteServiceConfig` types are also exported. See the [Vite integration guide](/docs/vite).

## `nitro/builder`

Programmatic API for tools that drive Nitro without the CLI (build wrappers, framework integrations).

| Export | Description |
| --- | --- |
| `createNitro` | Create a Nitro instance from an inline config (and `nitro.config` in `rootDir`). |
| `loadOptions` | Load and resolve Nitro options without creating an instance. |
| `prepare` | Clean the output directories. |
| `copyPublicAssets` | Copy public assets to the output directory. |
| `prerender` | Prerender routes. |
| `build` | Build the server bundle. |
| `createDevServer` | Create a development server for a Nitro instance. |
| `getBuildInfo` | Read `nitro.json` of the last build (accepts `rootDir` or `{ rootDir, outputDir }`). |
| `startPreview` | Start an in-process preview of a build (`{ rootDir, outputDir?, loader? }` returns `{ fetch, upgrade?, close }`). |
| `deploy` | Run the deploy command of the preset for an existing build (`deploy(nitro, { args? })`). |

```ts
import { build, copyPublicAssets, createNitro, deploy, prepare, prerender } from "nitro/builder";

const nitro = await createNitro({ rootDir: ".", dev: false, preset: "cloudflare_module" });
await prepare(nitro);
await copyPublicAssets(nitro);
await prerender(nitro);
await build(nitro);
await deploy(nitro, { args: ["--env", "staging"] });
await nitro.close();
```

`deploy` uses `commands.deploy` from the resolved options. It is either a shell command (run from `rootDir`, with `./` paths rewritten to the output directory) or a function for presets that deploy programmatically (such as `zephyr`). Presets that lack a deploy command throw an error.

## Other entries

The remaining subpaths (`nitro/meta` for package version and paths, `nitro/vite/runtime`, `nitro/tsconfig`) are internal and rarely needed in application code.
