Server Utilities
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" |
| Define a middleware | import { defineMiddleware } from "nitro" |
| Throw an HTTP error | import { HTTPError } from "nitro" |
| Read the body, query, cookies, ... | import { readBody, getQuery } from "nitro/h3" |
| Call your own routes internally | import { serverFetch } from "nitro" |
| Handle WebSocket connections | import { defineWebSocketHandler } from "nitro" |
| Add a runtime plugin | import { definePlugin } from "nitro" |
| Customize the error response | import { defineErrorHandler } from "nitro" |
| Cache a handler or function | import { defineCachedHandler, defineCachedFunction } from "nitro/cache" |
| Read/write key-value storage | import { useStorage } from "nitro/storage" |
| Query a SQL database | import { useDatabase } from "nitro/database" |
| Access runtime config | import { useRuntimeConfig } from "nitro/runtime-config" |
| Define and run tasks | import { defineTask, runTask } from "nitro/task" |
| Access the app instance and hooks | import { useNitroApp, useNitroHooks } from "nitro/app" |
Configure Nitro (nitro.config.ts) | import { defineConfig } from "nitro" |
| Use Nitro as a Vite plugin | import { nitro } from "nitro/vite" |
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. |
defineMiddleware | Define a middleware that runs before route handlers. |
defineWebSocketHandler | Define a WebSocket handler for a route file. |
definePlugin | Define a runtime plugin that runs on server startup. |
defineErrorHandler | Define a custom error handler to replace the built-in error page. |
defineConfig | Define Nitro configuration (used in nitro.config.ts, not in runtime code). |
defineRouteMeta | Attach route metadata such as OpenAPI specs (build-time macro). |
HTTPError | Throw HTTP errors with a status code: throw new HTTPError("Not found", { status: 404 }). |
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.
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:
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:
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 to a file that exports a custom error handler:
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:
import { definePlugin } from "nitro";
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook("request", (event) => {
console.log("request:", event.url.pathname);
});
});
See the plugins guide for more.
nitro/h3
Re-exports all H3 v2 utilities: readBody, getQuery, getCookie, setCookie, proxy, redirect, and many more.
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 };
});
nitro/cache
| Export | Description |
|---|---|
defineCachedHandler | Wrap an event handler with caching. |
defineCachedFunction | Cache the result of any (async) function. |
import { defineCachedHandler } from "nitro/cache";
export default defineCachedHandler(() => `Generated at ${new Date().toISOString()}`, {
maxAge: 60,
});
See the cache guide for options, cache keys, and invalidation.
nitro/storage
| Export | Description |
|---|---|
useStorage | Access the key-value storage layer, optionally scoped to a base (e.g. useStorage("data")). |
import { useStorage } from "nitro/storage";
await useStorage("data").set("visits", 42);
See the KV storage guide for mountpoints and drivers.
nitro/database
| Export | Description |
|---|---|
useDatabase | Access a configured SQL database connection (default: useDatabase(), named: useDatabase("users")). |
import { useDatabase } from "nitro/database";
const db = useDatabase();
const { rows } = await db.sql`SELECT * FROM users`;
See the database guide for connectors and configuration.
nitro/runtime-config
| Export | Description |
|---|---|
useRuntimeConfig | Access runtime configuration, overridable with NITRO_* environment variables. |
import { useRuntimeConfig } from "nitro/runtime-config";
const { apiToken } = useRuntimeConfig();
nitro/task
| Export | Description |
|---|---|
defineTask | Define a task in a server/tasks/ file. |
runTask | Run a task by name from anywhere in your server code. |
import { runTask } from "nitro/task";
const { result } = await runTask("db:migrate", { payload: { force: true } });
See the tasks guide — 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 (fetch, hooks, ...). |
useNitroHooks | Access the runtime hooks instance to register hooks outside of plugins. |
getRouteRules | Get the resolved route rules for a method and pathname: getRouteRules("GET", "/blog/post"). |
serverFetch, fetch | Same as the main entry exports. |
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. |
import { useRequest } from "nitro/context";
const request = useRequest();
useRequest is experimental: it requires the experimental.asyncContext: true 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.
import type { NitroRuntimeConfig } from "nitro/types";
nitro/vite
| Export | Description |
|---|---|
nitro | The Nitro Vite plugin. |
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";
export default defineConfig({
plugins: [nitro()],
});
The NitroPluginConfig and ServiceConfig types are also exported. See the Vite integration guide.
Other entries
The remaining subpaths (nitro/meta for package version and paths, nitro/builder, nitro/vite/runtime, nitro/tsconfig) are internal and rarely needed in application code.