Skip to content

Bindings

Once you have set up next-on-pages, you can access bindings from any route of your Next.js app via getRequestContext:

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);
}

Add bindings to your Pages project by adding them to your wrangler.toml configuration file.

TypeScript type declarations for bindings

To ensure that the env object from getRequestContext().env above has accurate TypeScript types, install @cloudflare/workers-types and create a TypeScript declaration file.

Install Workers Types:

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

Add Workers Types to your tsconfig.json file, replacing the date below with your project’s compatibility date:

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

Create an env.d.ts file in the root directory of your Next.js app, and explicitly declare the type of each binding:

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

Other Cloudflare APIs (cf, ctx)

Access context about the incoming request from the cf object, as well as lifecycle methods from the ctx object from the return value of getRequestContext():

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