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 doImport
Define an event handlerimport { defineHandler } from "nitro"
Define a middlewareimport { defineMiddleware } from "nitro"
Throw an HTTP errorimport { HTTPError } from "nitro"
Read the body, query, cookies, ...import { readBody, getQuery } from "nitro/h3"
Call your own routes internallyimport { serverFetch } from "nitro"
Handle WebSocket connectionsimport { defineWebSocketHandler } from "nitro"
Add a runtime pluginimport { definePlugin } from "nitro"
Customize the error responseimport { defineErrorHandler } from "nitro"
Cache a handler or functionimport { defineCachedHandler, defineCachedFunction } from "nitro/cache"
Read/write key-value storageimport { useStorage } from "nitro/storage"
Query a SQL databaseimport { useDatabase } from "nitro/database"
Access runtime configimport { useRuntimeConfig } from "nitro/runtime-config"
Define and run tasksimport { defineTask, runTask } from "nitro/task"
Access the app instance and hooksimport { useNitroApp, useNitroHooks } from "nitro/app"
Configure Nitro (nitro.config.ts)import { defineConfig } from "nitro"
Use Nitro as a Vite pluginimport { nitro } from "nitro/vite"

nitro

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

ExportDescription
defineHandlerDefine an event handler for a route or middleware file.
defineMiddlewareDefine a middleware that runs before route handlers.
defineWebSocketHandlerDefine a WebSocket handler for a route file.
definePluginDefine a runtime plugin that runs on server startup.
defineErrorHandlerDefine a custom error handler to replace the built-in error page.
defineConfigDefine Nitro configuration (used in nitro.config.ts, not in runtime code).
defineRouteMetaAttach route metadata such as OpenAPI specs (build-time macro).
HTTPErrorThrow HTTP errors with a status code: throw new HTTPError("Not found", { status: 404 }).
HTTPResponseReturn a body with a custom status and headers from a handler.
htmlTagged template literal returning an HTML response (text/html content type).
serverFetchCall your own routes internally, without a network round-trip.
fetchLike global fetch, but paths starting with / are routed to your own server.

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

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:

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:

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:

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:

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 for more.

nitro/h3

Re-exports all H3 v2 utilities: readBody, getQuery, getCookie, setCookie, proxy, redirect, and many more.

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 };
});
See the H3 utilities documentation for the full list.

nitro/cache

ExportDescription
defineCachedHandlerWrap an event handler with caching.
defineCachedFunctionCache 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

ExportDescription
useStorageAccess 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

ExportDescription
useDatabaseAccess 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

ExportDescription
useRuntimeConfigAccess runtime configuration, overridable with NITRO_* environment variables.
import { useRuntimeConfig } from "nitro/runtime-config";

const { apiToken } = useRuntimeConfig();

nitro/task

ExportDescription
defineTaskDefine a task in a server/tasks/ file.
runTaskRun 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.

ExportDescription
useNitroAppAccess the current Nitro app instance (fetch, hooks, ...).
useNitroHooksAccess the runtime hooks instance to register hooks outside of plugins.
getRouteRulesGet the resolved route rules for a method and pathname: getRouteRules("GET", "/blog/post").
serverFetch, fetchSame as the main entry exports.
import { useNitroHooks } from "nitro/app";

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

nitro/context

ExportDescription
useRequestAccess 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

ExportDescription
defineConfigSame 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

ExportDescription
nitroThe Nitro Vite plugin.
vite.config.ts
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.