Guide

服务器工具


¥Server Utils

享受自动导入的服务器工具,并使用你自己的工具进行扩展。

自动导入

¥Auto imports

阅读其余文档时,你可能会注意到工具示例中没有 imports。这是因为 Nitro 在完全支持摇树优化的情况下使用 unjs/unimport 自动导入工具,因此你无需手动操作!

¥When reading the rest of the docs, you might notice that there are no imports in examples for using utilities. It is because Nitro uses unjs/unimport to auto import utilities when used with full tree-shaking support so you don't have to!

H3 工具

¥H3 utils

Nitro 启用所有 H3 工具 的自动导入功能,因此你无需手动导入即可使用 defineEventHandlerreadBody 等。

¥Nitro enables all h3 utils as auto imports so you can use defineEventHandler, readBody, etc. without manually importing them.

Read more in H3 Docs.

utils directory

You can add your application specific utils inside server/utils/ directory and they will be auto-imported when used. Every export in the utils directory and its subdirectories will become available globally in your application.

Example: Create a server/utils/sum.ts file where a function useSum is exported:

server/utils/sum.ts
export function useSum(a: number, b: number) { return a + b }

Use it in your server/routes/index.ts file without importing it:

server/routes/index.ts
export default defineEventHandler(() => {
  const sum = useSum(1, 2) // auto-imported
  return { sum }
})

Nitro utils

Nitro also exposes several built-in utils:

  • defineCachedFunction(fn, options) / cachedFunction(fn, options)
  • defineCachedEventHandler(handler, options) / cachedEventHandler(handler, options)
  • defineRenderHandler(handler)
  • defineRouteMeta(options) (experimental)
  • useRuntimeConfig(event?)
  • useAppConfig(event?)
  • useStorage(base?)
  • useNitroApp()
  • defineNitroPlugin(plugin)
  • nitroPlugin(plugin)
  • getRouteRules(event)

::

read-more{to="https://github.com/nitrojs/nitro/blob/v2/src/core/config/resolvers/imports.ts#L58"} 检查 源代码 以获取可用的 Nitro 自动导入列表。::

¥read-more{to="https://github.com/nitrojs/nitro/blob/v2/src/core/config/resolvers/imports.ts#L58"} Check the source code for list of available Nitro auto imports. ::

运行 preparedev 命令时,全局自动导入的类型会自动生成。IDE 支持信息,请参阅 TypeScript 指南。

手动导入

¥Manual imports

对于某些特殊情况(IDE 支持和 node_modules 中的库),无法依赖自动导入。

¥For some edge cases (IDE support and libraries in node_modules) it is impossible to rely on auto imports.

你可以从虚拟 #imports 文件中显式导入它们。

¥You can explicitly import them from virtual #imports file.

手动从 #imports 导入仍然具有 tree-shaking 的优势。
server/plugins/test.ts
import { useStorage } from '#imports'

异步上下文(实验性)

¥Async Context (Experimental)

Nitro(2.6+)启用了全新的服务器开发体验,将应用逻辑拆分为更小的 "composable" 工具,这些工具彼此完全解耦,并且可以直接访问共享上下文(请求事件),而无需传递它。此模式的灵感来自 Vue Composition API,并由 unjs/unctx 提供支持。

¥Nitro (2.6+) enables a new server development experience in order to split application logic into smaller "composable" utilities that are fully decoupled from each other and can directly access a shared context (request event) without needing it to be passed along. This pattern is inspired from Vue Composition API and powered by unjs/unctx.

此功能目前支持 Node.js 和 Bun 运行时,其他支持 AsyncLocalStorage 接口的预设也即将支持此功能。

为了启用异步上下文功能,你必须启用 asyncContext 标志:

¥In order to enable async context feature, you have to enable asyncContext flag:

export default defineNitroConfig({
  experimental: {
    asyncContext: true
  }
});

启用此标志后,你可以在任何工具或可组合项中使用 useEvent()(自动导入)来访问请求事件,而无需手动传递:

¥After enabling this flag, you can use useEvent() (auto imported) in any utility or composable to access the request event without manually passing it along:

// server/routes/index.ts
export default defineEventHandler(async () => {
  const user = await useAuth()
})

// server/utils/auth.ts
export function useAuth() {
  return useSession(useEvent())
}