绑定(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 --env-interface CloudflareEnv
这将生成一个 d.ts
文件并保存为 worker-configuration.d.ts
。
为确保你的类型始终保持最新,请在每次修改配置文件后运行 wrangler types --env-interface CloudflareEnv
。
其他 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();
// ...
}