Loading...
Loading...
Connection pooling and caching for PostgreSQL and MySQL databases. Load when connecting Workers to existing Postgres/MySQL, reducing connection overhead, using Drizzle/Prisma with external databases, or migrating traditional database apps to the edge.
npx skill4agent add null-shot/cloudflare-skills hyperdrive# Create a Hyperdrive configuration for your database
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
# Copy the ID from the output for your wrangler.jsoncwrangler.jsonc{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<YOUR_DATABASE_ID>"
}
]
}| Operation | API |
|---|---|
| Get connection string | |
| Connect with Postgres.js | |
| Query with Postgres.js | |
| No cleanup needed | Hyperdrive handles connection pooling—don't call |
| List configs | |
| Get config details | |
| Update config | |
| Delete config | |
npm install postgresimport postgres from "postgres";
export interface Env {
// If you set another name in the Wrangler config file as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a database client that connects to your database via Hyperdrive.
//
// Hyperdrive generates a unique connection string you can pass to
// supported drivers, including node-postgres, Postgres.js, and the many
// ORMs and query builders that use these drivers.
const sql = postgres(env.HYPERDRIVE.connectionString);
try {
// Test query
const results = await sql`SELECT * FROM pg_tables`;
// Return result rows as JSON
return Response.json(results);
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;sql.end()// ❌ DON'T DO THIS
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
await sql.end(); // DON'T close the connection
// ✅ DO THIS INSTEAD
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
// Let Hyperdrive manage the connection| Driver | Package | Notes |
|---|---|---|
| Postgres.js | | Recommended - 3.4.5 or later |
| node-postgres | | Widely used, works well |
| Drizzle ORM | | Use with postgres driver |
| Prisma | | Add |
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
export default {
async fetch(request, env, ctx): Promise<Response> {
const client = postgres(env.HYPERDRIVE.connectionString);
const db = drizzle(client);
const results = await db.select().from(users);
return Response.json(results);
}
};?connection_limit=1import { PrismaClient } from '@prisma/client';
export default {
async fetch(request, env, ctx): Promise<Response> {
// Append connection_limit=1 for Prisma
const prisma = new PrismaClient({
datasourceUrl: env.HYPERDRIVE.connectionString + '?connection_limit=1'
});
const users = await prisma.user.findMany();
return Response.json(users);
}
};# Create MySQL Hyperdrive config
npx wrangler hyperdrive create my-mysql \
--connection-string="mysql://user:password@host:3306/database"import { connect } from '@planetscale/database';
export default {
async fetch(request, env, ctx): Promise<Response> {
const conn = connect({ url: env.HYPERDRIVE.connectionString });
const results = await conn.execute('SELECT * FROM users');
return Response.json(results.rows);
}
};# Default: cache enabled with 60s TTL
npx wrangler hyperdrive create my-db \
--connection-string="postgres://..." \
--caching-disabled=false \
--max-age=60?connection_limit=1--remotewrangler.jsonc?connection_limit=1# Use --remote to test with actual Hyperdrive
npx wrangler dev --remote
# Or use local connection string for development
# (add to .dev.vars)
HYPERDRIVE_CONNECTION_STRING=postgres://localhost:5432/mydb