Cloudflare
历史版本
Release 0.3
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 = (await getCloudflareContext()).env.MY_KV_NAMESPACE;
  await myKv.put("foo", "bar");
  const foo = await myKv.get("foo");
 
  return new Response(foo);
}

如何向 Worker 添加绑定

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

绑定类型的 TypeScript 声明

为确保上述 (await 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 } = await getCloudflareContext();
 
  // ...
}