Providers

Cloudflare

将 Nitro 应用部署到 Cloudflare。

Cloudflare Pages

预设:cloudflare_pages

¥Preset: cloudflare_pages

Read more in Cloudflare Pages.
这是 Cloudflare 部署的推荐预设,如果你需要特殊功能,请考虑使用其他预设。
zero configuration 可以与此提供程序集成。

Nitro 会自动生成一个 _routes.json 文件,用于控制哪些路由从文件获取服务,哪些路由从 Worker 脚本获取服务。可以使用配置选项 cloudflare.pages.routes阅读更多)覆盖自动生成的路由文件。

¥Nitro automatically generates a _routes.json file that controls which routes get served from files and which are served from the Worker script. The auto-generated routes file can be overridden with the config option cloudflare.pages.routes (read more).

使用预设构建应用

¥Building your Application using the preset

此预设仅适用于应用构建过程。

¥The preset only applies for the application build process.

如果你使用 Cloudflare 页面 GitHub/GitLab 集成,并且不需要在本地预览应用,则 Nitro 不需要任何类型的配置。当你推送到你的代码库时,Cloudflare Pages CI/CD 流程将自动构建你的项目,Nitro 将检测正确的环境并相应地构建你的应用。

¥If you use the Cloudflare Pages GitHub/GitLab integration, and you don't need to preview your application locally, Nitro does not require any type of configuration. When you push to your repository, the Cloudflare Pages CI/CD process will automatically build your project and Nitro will detect the correct environment and build your application accordingly.

如果你想在本地预览应用和/或手动部署,则在构建应用时,你需要让 Nitro 知道目标环境是 Cloudflare Pages,你可以通过两种方式实现:

¥If instead you want preview your application locally and/or manually deploy it, when building the application you will need to let Nitro know that the target environment is the Cloudflare Pages one, you can do that in two ways:

  • 通过在运行构建过程时定义 NITRO_PRESETSERVER_PRESET 环境变量并将其设置为 cloudflare_pages,如下所示:
    NITRO_PRESET=cloudflare_pages npm run build
    
  • 或者通过更新你的 Nitro 预设配置
    "preset": "cloudflare_pages",
    

    然后运行标准构建命令:
    npm run build

Wrangler

要在本地预览你的应用或手动部署,你需要使用 wrangler CLI 工具,只需将其安装为节点依赖即可:

¥To preview your application locally or manually deploy it you will need to use the wrangler CLI tool, simply install it as a node dependency:

npm i wrangler

本地预览你的应用

¥Preview your app locally

构建应用后,你可以通过运行以下命令使用 wrangler 在本地预览它:

¥After having built your application you can preview it locally with wrangler by running:

npx wrangler pages dev dist

从本地部署使用 wrangler 的机器

¥Deploy from your local machine using wrangler

构建应用后,你可以使用 wrangler 手动部署它,为此,请先确保登录你的 Cloudflare 账户:

¥After having built your application you can manually deploy it with wrangler, in order to do so first make sure to be logged into your Cloudflare account:

npx wrangler login

然后,你可以使用以下命令部署应用:

¥Then you can deploy the application with:

npx wrangler pages deploy dist

Cloudflare Module Workers

预设:cloudflare_module

¥Preset: cloudflare_module

**注意:**此预设使用 module worker syntax 进行部署。

使用 Workers 时,你需要在根目录中创建一个 wrangler.toml 文件。要将 Workers 与 静态资源(与 limitations 一起测试)一起使用,你还需要在 wrangler.toml 文件和 nitro 配置文件中将兼容日期设置为 2024-09-19 或更高版本。

¥When using Workers you will need a wrangler.toml file, in your root directory. To using Workers with Static Assets (BETA with limitations), you also need a compatibility date set to 2024-09-19 or later, in your wrangler.toml file and nitro configuration file.

以下展示了 Nitro 应用的典型 wrangler.toml 文件和 nitro.config.ts 文件:

¥The following shows a typical wrangler.toml file and a nitro.config.ts file for a Nitro application:

export default defineNitroConfig({
    compatibilityDate: "2024-09-19",
})
wrangler.toml
name = "nitro-app"
compatibility_date = "2024-09-19"
main = "./.output/server/index.mjs"
assets = { directory = "./.output/public/", binding = "ASSETS" }

运行时钩子

¥Runtime hooks

你可以使用下面的 运行时钩子 来扩展 Worker 处理程序

¥You can use runtime hooks below in order to extend worker handlers.

Read more in Guide > Plugins#nitro Runtime Hooks.

本地预览你的应用

¥Preview your app locally

你可以使用 wrangler 在本地预览你的应用:

¥You can use wrangler, to preview your app locally:

NITRO_PRESET=cloudflare npm run build

# If you have added a 'wrangler.toml' file like above in the root of your project:
npx wrangler dev

# If you don't have a 'wrangler.toml', directly use:
npx wrangler dev .output/server/index.mjs --site .output/public

从本地部署使用 wrangler 的机器

¥Deploy from your local machine using wrangler

安装 wrangler 并登录你的 Cloudflare 账户:

¥Install wrangler and login to your Cloudflare account:

npm i wrangler
wrangler login

使用 cloudflare_module 预设生成你的应用:

¥Generate your app using the cloudflare_module preset:

NITRO_PRESET=cloudflare_module npm run build

然后,你可以在本地预览:

¥You can then preview it locally:

# If you have a 'wrangler.toml' like above:
npx wrangler dev

# If you don't have a 'wrangler.toml':
npx wrangler dev .output/server/index.mjs --site .output/public

并发布:

¥and publish it:

npx wrangler deploy

Cloudflare Service Workers

预设:cloudflare

¥Preset: cloudflare

**注意:**此预设使用 service worker syntax 进行部署。

::warning 注意:此预设已弃用。::

¥::warning Note: This preset is deprecated. ::

此预设的工作方式与上面介绍的 cloudflare_module 预设的工作方式相同,唯一的区别在于此预设继承了该语法带来的所有 disadvantages 功能。

¥The way this preset works is identical to that of the cloudflare_module one presented above, with the only difference being that such preset inherits all the disadvantages that such syntax brings.

使用 GitHub Actions 在 CI/CD 中部署

¥Deploy within CI/CD using GitHub Actions

无论你使用的是 Cloudflare Pages 还是 Cloudflare Workers,你都可以使用 Wrangler GitHub Actions 部署你的应用。

¥Regardless on whether you're using Cloudflare Pages or Cloudflare workers, you can use the Wrangler GitHub actions to deploy your application.

**注意:**务必添加 instruct Nitro to use the correct preset(所有预设,包括 cloudflare_pages 预设,都必须添加)。

环境变量

¥Environment Variables

Nitro 允许你使用 process.envimport.meta.env 或运行时配置来统一访问环境变量。

¥Nitro allows you to universally access environment variables using process.env or import.meta.env or the runtime config.

确保仅在事件生命周期内访问环境变量,而不是在全局上下文中访问,因为 Cloudflare 仅在请求生命周期内(而非之前)提供这些变量。

示例:如果你已设置 SECRETNITRO_HELLO_THERE 环境变量,则可以通过以下方式访问它们:

¥Example: If you have set the SECRET and NITRO_HELLO_THERE environment variables set you can access them in the following way:

console.log(process.env.SECRET) // note that this is in the global scope! so it doesn't actually work and the variable is undefined!

export default defineEventHandler((event) => {
  // note that all the below are valid ways of accessing the above mentioned variables
  useRuntimeConfig(event).helloThere
  useRuntimeConfig(event).secret
  process.env.NITRO_HELLO_THERE
  import.meta.env.SECRET
});

在开发模式下指定变量

¥Specify Variables in Development Mode

开发时,你可以使用 .env 文件指定环境变量:

¥For development, you can use a .env file to specify environment variables:

NITRO_HELLO_THERE="captain"
SECRET="top-secret"
**注意:**请确保将 .env 添加到 .gitignore 文件中,以免提交该文件,因为该文件可能包含敏感信息。

指定本地预览环境变量

¥Specify Variables for local previews

构建完成后,当你使用 wrangler devwrangler pages dev 在本地测试项目时,为了访问环境变量,你需要在项目根目录中的 .dev.vars 文件中指定(如 页面Workers 文档中所述)。

¥After build, when you try out your project locally with wrangler dev or wrangler pages dev, in order to have access to environment variables you will need to specify the in a .dev.vars file in the root of your project (as presented in the Pages and Workers documentation).

如果你在开发过程中使用 .env 文件,那么你的 .dev.vars 文件应该与其完全相同。

¥If you are using a .env file while developing, your .dev.vars should be identical to it.

**注意:**请确保将 .dev.vars 添加到 .gitignore 文件中,以免提交该文件,因为该文件可能包含敏感信息。

指定生产环境变量

¥Specify Variables for Production

对于生产环境,请使用 cloudflare 仪表板或 wrangler secret 命令设置环境变量和密钥。

¥For production, use the cloudflare dashboard or the wrangler secret command to set environment variables and secrets.

使用 wrangler.toml 指定变量

¥Specify Variables using wrangler.toml

你可以指定一个自定义 wrangler.toml 文件并在其中定义变量。

¥You can specify a custom wrangler.toml file and define vars inside.

::warning 请注意,不建议对敏感数据使用此方法。::

¥::warning Note that this isn't recommend for sensitive data. ::

示例:

¥Example:

wrangler.toml
# Shared
[vars]
NITRO_HELLO_THERE="general"
SECRET="secret"

# Override values for `--env production` usage
[env.production.vars]
NITRO_HELLO_THERE="captain"
SECRET="top-secret"

直接访问 cloudflare 绑定

¥Direct access to cloudflare bindings

绑定允许你与 Cloudflare 平台的资源进行交互,例如键值数据存储 (KVs) 和无服务器 SQL 数据库 (D1s)。

¥Bindings are what allows you to interact with resources from the Cloudflare platform, examples of such resources are key-value data storages (KVs) and serverless SQL databases (D1s).

有关绑定及其使用方法的更多详细信息,请参阅 Cloudflare PagesWorkers 文档。
Nitro 提供高级 API 与 KV 存储数据库 等原语交互,强烈建议你优先使用它们,而不是直接依赖底层 API,以确保使用稳定性。
Read more in Database Layer.
Read more in KV Storage.

在运行时,你可以通过访问请求事件的 context.cloudflare.env 字段来访问绑定。例如,你可以这样访问 D1 绑定:

¥In runtime, you can access bindings from the request event, by accessing its context.cloudflare.env field, this is for example how you can access a D1 bindings:

defineEventHandler(async (event) => {
  const { cloudflare } = event.context
  const stmt = await cloudflare.env.MY_D1.prepare('SELECT id FROM table')
  const { results } = await stmt.all()
})

访问本地环境中的绑定

¥Access to the bindings in local env

为了在本地开发模式下访问绑定,无论选择哪种预设,建议将 wrangler.toml 文件(以及 .dev.vars 文件)与 nitro-cloudflare-dev 模块 结合使用,如下所示。

¥In order to access bindings during local dev mode, regardless of the chosen preset, it is recommended to use a wrangler.toml file (as well as a .dev.vars one) in combination with the nitro-cloudflare-dev module as illustrated below.

nitro-cloudflare-dev 模块处于实验阶段。Nitro 团队正在研究一种更原生的集成方式,这可能在不久的将来使该模块不再需要。

为了在开发模式下访问绑定,我们首先在 wrangler.toml 文件中定义绑定,例如,你可以这样定义变量和键值命名空间:

¥In order to access bindings in dev mode we start by defining the bindings in a wrangler.toml file, this is for example how you would define a variable and a KV namespace:

wrangler.toml
[vars]
MY_VARIABLE="my-value"

[[kv_namespaces]]
binding = "MY_KV"
id = "xxx"
仅识别默认环境中的绑定。

接下来,我们将安装 nitro-cloudflare-dev 模块以及所需的 wrangler 包(如果尚未安装):

¥Next we install the nitro-cloudflare-dev module as well as the required wrangler package (if not already installed):

npm i -D nitro-cloudflare-dev wrangler

然后定义模块:

¥Then define module:

import nitroCloudflareBindings from "nitro-cloudflare-dev";

export default defineNitroConfig({
  modules: [nitroCloudflareBindings],
});

从现在开始,运行时

¥From this moment, when running

npm run dev

你将能够从请求事件访问 MY_VARIABLEMY_KV,如上所示。

¥you will be able to access the MY_VARIABLE and MY_KV from the request event just as illustrated above.