Cloudflare
历史版本
Release 0.5
Bindings

绑定(Bindings)

绑定 (opens in a new tab)允许你的 Worker 与 Cloudflare 开发者平台上的资源进行交互。当你在 Worker 上声明一个绑定时,实际上是授予它特定的能力,例如能够读写 R2 (opens in a new tab) 存储桶中的文件。

如何配置你的 Next.js 应用以访问绑定

安装 @opennextjs/cloudflare (opens in a new tab),然后按照入门指南所述,在你的 Next.js 应用根目录中添加一个 wrangler 配置文件 (opens in a new tab)

如何在 Next.js 应用中访问绑定

你可以通过 getCloudflareContext 从 Next.js 应用的任何路由访问绑定 (opens in a new tab)

import { getCloudflareContext } from "@opennextjs/cloudflare";
 
export async function GET(request) {
  let responseText = "Hello World";
 
  const myKv = getCloudflareContext().env.MY_KV_NAMESPACE;
  await myKv.put("foo", "bar");
  const foo = await myKv.get("foo");
 
  return new Response(foo);
}

getCloudflareContext 只能在 SSG 路由中以"异步模式"使用(使其返回一个 Promise),要以这种方式运行函数,只需提供一个带有 async 设置为 true 的选项参数:

const context = await getCloudflareContext({ async: true });

警告:在 SSG 期间需要特别小心,因为静态页面生成时会使用存储在 .dev.vars 文件中的密钥以及来自绑定的本地开发值(如保存在本地 KV 中的值)。

如何为你的 Worker 添加绑定

通过将绑定添加到你的 wrangler 配置文件 (opens in a new tab) 来为 Worker 添加绑定。

绑定的 TypeScript 类型声明

为确保上述 getCloudflareContext().env 返回的 env 对象具有准确的 TypeScript 类型,请运行以下 Wrangler 命令来 生成与你的 Worker 配置匹配的类型 (opens in a new tab)

npx wrangler types --experimental-include-runtime

这将生成一个 d.ts 文件并(默认情况下)将其保存到 .wrangler/types/runtime.d.ts。命令输出会提示你将此文件添加到 tsconfig.jsoncompilerOptions.types 数组中。

如果你想将该文件提交到 git,可以提供一个自定义路径。例如,以下命令会将 runtime.d.ts 文件保存到项目根目录:

npx wrangler types --experimental-include-runtime="./runtime.d.ts"

为确保你的类型始终是最新的,请在每次修改配置文件后运行 wrangler types --experimental-include-runtime

其他 Cloudflare API (cf, ctx)

你可以从 cf 对象 (opens in a new tab) 获取有关传入请求的上下文信息,以及从 getCloudflareContext() (opens in a new tab) 返回值的 ctx 对象 (opens in a new tab) 中获取生命周期方法:

import { getCloudflareContext } from "@opennextjs/cloudflare";
 
export async function GET(request) {
  const { env, cf, ctx } = getCloudflareContext();
 
  // ...
}