nextjs使用cloudflare的绑定
约 460 字大约 2 分钟
2025-10-12
https://opennext.js.org/cloudflare/bindings
这里我们要准备一个第三方数据库,比如 neon。 然后使用 cloudflare 的绑定功能,就可以直接使用第三方数据库。cloudflare 就会维护一个连接池了,加速请求。
使用方法
API routes
在 nextjs 的 api 里面可以使用下面的方法。 这种方法可以直接全局获取到 cloudflare 的 env。
import { getCloudflareContext } from "@opennextjs/cloudflare";
export async function GET(request) {
const myKv = getCloudflareContext().env.MY_KV_NAMESPACE;
await myKv.put("foo", "bar");
const foo = await myKv.get("foo");
return new Response(foo);
}SSG routes
getCloudflareContext can only be used in SSG routes in "async mode" (making it return a promise), to run the function in such a way simply provide an options argument with async set to true:
const context = await getCloudflareContext({ async: true });WARNING: During SSG caution is advised since secrets (stored in .dev.vars files) and local development values from bindings (like values saved in a local KV) will be used for the pages static generation.
cloudflare bandings
如果没有使用 you 的 cloudflare 绑定,在 nextjs 访问外部数据库服务的时候 延迟非常大,我测试了一下,如果在 worker 里面连接我国内的数据库,延迟有 8 秒。
绑定之后,延迟非常小,我测试了一下,在 worker 里面连接我国内的数据库,延迟只有 1 秒。
数据库我选择的是
https://console.neon.tech
他可以新建 20 个免费的库。

绑定的配置

在 cloudflare 后台绑定以后,需要在配置文件里面加上:
[[ d1_databases ]]
binding = "your binding name"
database_name = "your database name"
database_id = "your database id"
migrations_dir = "drizzle/migrations"
[[hyperdrive]]
binding = "your binding name"
id = "your hyperdrive id"
localConnectionString = "your hyperdrive local connection string"使用方法
import { getCloudflareContext } from "@opennextjs/cloudflare";
export async function GET(req: Request) {
let ctx = getCloudflareContext();
//比如d1绑定的name是 DB
let db = ctx.env.DB;
//比如hyperdrive绑定的name是 SQL_URL
let localConnectionString = ctx.env.SQL_URL.connectionString;
//说明:hyperdrive一般用来存数据库,比如mysql,pgsql 等的连接信息
}