---
title: "服务器兼容性"
description: "构建一个模块，同时支持 Nuxt 4 和 Nuxt 5，无论底层使用哪种服务器运行时。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/modules/server-compatibility"
---
# 服务器兼容性

> 构建一个模块，同时支持 Nuxt 4 和 Nuxt 5，无论底层使用哪种服务器运行时。

Nuxt 支持多种服务器运行时。Nuxt 3 和 4 使用 Nitro v2（`nitropack`），它使用 `h3` v1；Nuxt 5 默认使用 Nitro v3（`nitro`），它使用 `h3` v2。也可以使用基于 Web API 的自定义服务器运行时，该运行时在任何环境中都兼容（`nuxt/server`）。

本指南介绍如何编写一个服务器代码可在所有这些环境中运行的模块。

<note>

如果你的模块没有服务器代码，则无需关注本文内容。

</note>

## 推荐迁移方式

[`nuxt/server`](https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/server-imports) 是基于 Web API 编写通用服务器代码的导入入口，并随 Nuxt 4.6+ 一同发布。使用它编写的代码可运行于 `nitropack` v2、Nitro v3 以及其他服务器构建器（例如 `@nuxt/vite-server`）之下。

### 事件处理器

如果你要注册事件处理器，请保留当前的处理器（以兼容 Nuxt <4.6），并使用 `nuxt/server` 添加一个新的可移植处理器，然后同时注册两者。Nuxt 会注册应用可以运行的实现：在 Nitro v3 和其他构建器下使用可移植文件，在仍运行 `nitropack` v2 的主机上使用 v2 文件。

```ts [module.ts]
import { addServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  meta: { name: 'my-module' },
  setup () {
    const { resolve } = createResolver(import.meta.url)

    addServerHandler({
      route: '/api/my-module/status',
      handler: {
        nuxt: resolve('./runtime/server/status'),
        nitro2: resolve('./runtime/server/status.legacy'),
      },
    })
  },
})
```

大多数情况下，你的处理器文件只有导入内容不同：

<code-group>

```ts [runtime/server/status.ts]
import { defineEventHandler, useRuntimeConfig } from 'nuxt/server'

export default defineEventHandler(() => ({
  version: useRuntimeConfig().public.myModule.version,
}))
```

```ts [runtime/server/status.legacy.ts]
// @ts-expect-error `#imports` is typed for the app, not the server build
import { useRuntimeConfig } from '#imports'
import { defineEventHandler } from 'h3'

export default defineEventHandler(event => ({
  version: useRuntimeConfig(event).public.myModule.version,
}))
```

</code-group>

这些键指出了每个文件所依赖的服务器 API：

<table>
<thead>
  <tr>
    <th>
      键
    </th>
    
    <th>
      文件导入的内容
    </th>
    
    <th>
      运行位置
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        nuxt
      </code>
    </td>
    
    <td>
      仅 <code>
        nuxt/server
      </code>
    </td>
    
    <td>
      Nuxt 4.6 起支持任何服务器构建器
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        nitro2
      </code>
    </td>
    
    <td>
      <code>
        h3
      </code>
      
      、<code>
        nitropack/runtime
      </code>
      
      、<code>
        #imports
      </code>
    </td>
    
    <td>
      <code>
        nitropack
      </code>
      
       v2
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        nitro3
      </code>
    </td>
    
    <td>
      <code>
        nitro
      </code>
      
      、<code>
        nitro/h3
      </code>
    </td>
    
    <td>
      Nitro 服务器构建器 v3
    </td>
  </tr>
</tbody>
</table>

Nuxt 会根据用户使用的服务器构建器，选择最合适的处理器。如果你注册的处理器无法由用户的服务器构建器运行，则会跳过该处理器并发出警告。

<tip>

仅在代码需要 Nitro v3 独有的 API 时使用 `nitro3`。使用 `nuxt/server` 能让你的代码在未来保持更好的可移植性。

</tip>

使用此模式意味着你将同时支持 Nuxt 的旧版本（<4.6）和新版本（包括 Nuxt 5）。

<important>

由于此模式依赖 `@nuxt/kit` 工具函数，请确保将其添加到模块的 `dependencies` 中，[模块 starter](https://nuxt.zhcndoc.com/docs/4.x/guide/modules/getting-started) 会为你完成此设置。如果你将 `@nuxt/kit` 移到了 `peerDependencies`，则会使用应用程序的版本。

</important>

### 服务器插件

服务器插件也支持变体，但它们专用于 Nitro，因此没有可供注册的通用 `nuxt` 变体。

<tip>

由于 `defineNitroPlugin` 是一个恒等函数，你可以将它替换为类型注解，从而编写同时适用于 `nitro2` 和 `nitro3` 的代码。

</tip>

```ts [module.ts]
import { addNitroPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  meta: { name: 'my-module' },
  setup () {
    const { resolve } = createResolver(import.meta.url)

    addNitroPlugin({
      nitro2: resolve('./runtime/server/plugin.legacy'),
      nitro3: resolve('./runtime/server/plugin'),
    })
  },
})
```

<note>

`addServerImports`、`addServerImportsDir` 和 `addServerTemplate` 在 Nitro 2 和 3 中没有区别。如果你的代码存在差异，可以使用 `getNitroVersion` 来有条件地注册不同的导入项或模板。

</note>

### 声明无法推断的内容

Nuxt 会读取已注册文件的导入项，以判断该文件使用的 API，因此你无需声明其兼容性。但如果这还不够，你可以设置 `meta.compatibility.server`：

```ts [module.ts]
export default defineNuxtModule({
  meta: {
    name: 'my-module',
    compatibility: { server: 'nuxt' },
  },
})
```

如果我们无法判断，代码将被视为 `nitro2`。

## Nitro 专用代码

`nuxt/server` 涵盖请求和响应相关工作：处理器、错误、路由参数、查询和请求体的读取与验证、标头、CORS、Cookie、会话、重定向、路由规则、运行时配置和应用配置。但 Nitro 涵盖的内容远不止这些，因此如果你需要以下任一功能，可能需要在 `nitro2` 或 `nitro3` 文件中继续使用 Nitro 自身的导入项。

使用与文件对应版本的模块说明符。导入 `nitro/*` 的文件会被视为 Nitro 3 代码，因此 `nitro2` 文件必须改为导入 `h3` 和 `nitropack/*`：

<table>
<thead>
  <tr>
    <th>
      区域
    </th>
    
    <th>
      在 <code>
        nitro2
      </code>
      
       文件中
    </th>
    
    <th>
      在 <code>
        nitro3
      </code>
      
       文件中
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      存储：<code>
        useStorage()
      </code>
      
       及其驱动配置
    </td>
    
    <td>
      <code>
        nitropack/runtime
      </code>
    </td>
    
    <td>
      <code>
        nitro/storage
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      缓存：<code>
        defineCachedEventHandler()
      </code>
      
      、<code>
        defineCachedFunction()
      </code>
    </td>
    
    <td>
      <code>
        nitropack/runtime
      </code>
    </td>
    
    <td>
      <code>
        nitro/cache
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      服务器插件
    </td>
    
    <td>
      来自 <code>
        nitropack/runtime
      </code>
      
       的 <code>
        defineNitroPlugin()
      </code>
    </td>
    
    <td>
      来自 <code>
        nitro
      </code>
      
       的 <code>
        definePlugin()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      运行时钩子，包括 <code>
        render:html
      </code>
    </td>
    
    <td>
      来自 <code>
        nitropack/runtime
      </code>
      
       的 <code>
        useNitroApp().hooks
      </code>
    </td>
    
    <td>
      来自 <code>
        nitro/app
      </code>
      
       的 <code>
        useNitroHooks()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      应用相对 fetch
    </td>
    
    <td>
      来自 <code>
        nitropack/runtime
      </code>
      
       的 <code>
        useNitroApp().localFetch
      </code>
    </td>
    
    <td>
      来自 <code>
        nitro
      </code>
      
       的 <code>
        serverFetch()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      延迟处理器：<code>
        lazyEventHandler()
      </code>
    </td>
    
    <td>
      <code>
        h3
      </code>
    </td>
    
    <td>
      <code>
        nitro/h3
      </code>
    </td>
  </tr>
</tbody>
</table>

`nuxt/server` 也不支持任务。

<read-more to="https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/server-imports#reaching-past-the-surface">

了解哪些 h3 辅助函数适用于可移植事件，哪些需要 Nitro 专用工具。

</read-more>

## Nitro v3 中值得注意的变更

如果你只发布 `nitro2` 文件，它仍可通过 Nitro v2 兼容层在 Nuxt 5 上运行。相关说明以及 Nitro v3 中发生变化的行为，请参阅 [Nuxt 5 模块服务器兼容性指南](https://nuxt.com/docs/5.x/guide/modules/server-compatibility)。


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
