コンテンツにスキップ

バインディング

次のページのセットアップが完了したら、getRequestContextを介してNext.jsアプリの任意のルートからバインディングにアクセスできます:

import { getRequestContext } from "@cloudflare/next-on-pages";
export const runtime = "edge";
export async function GET(request) {
let responseText = "Hello World";
const myKv = getRequestContext().env.MY_KV_NAMESPACE;
await myKv.put("foo", "bar");
const foo = await myKv.get("foo");
return new Response(foo);
}

あなたの wrangler.toml 設定ファイルに追加することでページプロジェクトにバインディングを追加します。

バインディングのための TypeScript 型宣言

上記の getRequestContext().env からの env オブジェクトが正確な TypeScript 型を持つことを保証するために、@cloudflare/workers-typesをインストールし、TypeScript 宣言ファイルを作成します。

Workers Types をインストール:

Terminal window
npm install --save-dev @cloudflare/workers-types

Workers Types を tsconfig.json ファイルに追加し、以下の日付をプロジェクトの互換性の日付に置き換えます:

tsconfig.json
"types": [
"@cloudflare/workers-types/2024-07-29"
]

Next.js アプリのルートディレクトリに env.d.ts ファイルを作成し、各バインディングの型を明示的に宣言します:

env.d.ts
interface CloudflareEnv {
MY_KV_1: KVNamespace;
MY_KV_2: KVNamespace;
MY_R2: R2Bucket;
MY_DO: DurableObjectNamespace;
}

その他の Cloudflare API (cf, ctx)

cf オブジェクトからの受信リクエストに関するコンテキストや、getRequestContext()の戻り値からのライフサイクルメソッドにアクセスします:

import { getRequestContext } from "@cloudflare/next-on-pages";
export const runtime = "edge";
export async function GET(request) {
const { env, cf, ctx } = getRequestContext();
// ...
}