cloudflare-hyperdrive
Connect Workers to PostgreSQL/MySQL with Hyperdrive's global pooling and caching. Use when: connecting to existing databases, setting up connection pools, using node-postgres/mysql2, integrating Drizzle/Prisma, or troubleshooting pool acquisition failures, TLS errors, nodejs_compat missing, or eval() disallowed.
What this skill does
# Cloudflare Hyperdrive **Status**: Production Ready ✅ **Last Updated**: 2025-11-23 **Dependencies**: cloudflare-worker-base (recommended for Worker setup) **Latest Versions**: [email protected], [email protected]+ (minimum), [email protected], [email protected] **Recent Updates (2025)**: - **July 2025**: Configurable connection counts (min 5, max ~20 Free/~100 Paid) - **May 2025**: 5x faster cache hits (regional prepared statement caching), FedRAMP Moderate authorization - **April 2025**: Free plan availability (10 configs), MySQL GA support - **March 2025**: 90% latency reduction (pools near database), IP access control (standard CF IP ranges) - **nodejs_compat_v2**: pg driver no longer requires node_compat mode (auto-enabled with compatibility_date 2024-09-23+) - **Limits**: 25 Hyperdrive configurations per account (Paid), 10 per account (Free) --- ## Quick Start (5 Minutes) ### 1. Create Hyperdrive Configuration ```bash # For PostgreSQL npx wrangler hyperdrive create my-postgres-db \ --connection-string="postgres://user:[email protected]:5432/database" # For MySQL npx wrangler hyperdrive create my-mysql-db \ --connection-string="mysql://user:[email protected]:3306/database" # Output: # ✅ Successfully created Hyperdrive configuration # # [[hyperdrive]] # binding = "HYPERDRIVE" # id = "a76a99bc-7901-48c9-9c15-c4b11b559606" ``` **Save the `id` value** - you'll need it in the next step! --- ### 2. Configure Bindings in wrangler.jsonc Add to your `wrangler.jsonc`: ```jsonc { "name": "my-worker", "main": "src/index.ts", "compatibility_date": "2024-09-23", "compatibility_flags": ["nodejs_compat"], // REQUIRED for database drivers "hyperdrive": [ { "binding": "HYPERDRIVE", // Available as env.HYPERDRIVE "id": "a76a99bc-7901-48c9-9c15-c4b11b559606" // From wrangler hyperdrive create } ] } ``` **CRITICAL:** - `nodejs_compat` flag is **REQUIRED** for all database drivers - `binding` is how you access Hyperdrive in code (`env.HYPERDRIVE`) - `id` is the Hyperdrive configuration ID (NOT your database ID) --- ### 3. Install Database Driver ```bash # For PostgreSQL (choose one) npm install pg # node-postgres (most common) npm install postgres # postgres.js (modern, minimum v3.4.5) # For MySQL npm install mysql2 # mysql2 (minimum v3.13.0) ``` --- ### 4. Query Your Database **PostgreSQL with node-postgres (pg):** ```typescript import { Client } from "pg"; type Bindings = { HYPERDRIVE: Hyperdrive; }; export default { async fetch(request: Request, env: Bindings, ctx: ExecutionContext) { const client = new Client({ connectionString: env.HYPERDRIVE.connectionString }); await client.connect(); try { const result = await client.query('SELECT * FROM users LIMIT 10'); return Response.json({ users: result.rows }); } finally { // Clean up connection AFTER response is sent ctx.waitUntil(client.end()); } } }; ``` **MySQL with mysql2:** ```typescript import { createConnection } from "mysql2/promise"; export default { async fetch(request: Request, env: Bindings, ctx: ExecutionContext) { const connection = await createConnection({ host: env.HYPERDRIVE.host, user: env.HYPERDRIVE.user, password: env.HYPERDRIVE.password, database: env.HYPERDRIVE.database, port: env.HYPERDRIVE.port, disableEval: true // REQUIRED for Workers (eval() not supported) }); try { const [rows] = await connection.query('SELECT * FROM users LIMIT 10'); return Response.json({ users: rows }); } finally { ctx.waitUntil(connection.end()); } } }; ``` --- ### 5. Deploy ```bash npx wrangler deploy ``` **That's it!** Your Worker now connects to your existing database via Hyperdrive with: - ✅ Global connection pooling - ✅ Automatic query caching - ✅ Reduced latency (eliminates 7 round trips) --- ## How Hyperdrive Works Hyperdrive eliminates 7 connection round trips (TCP + TLS + auth) by: - Edge connection setup near Worker (low latency) - Connection pooling near database (March 2025: 90% latency reduction) - Query caching at edge (May 2025: 5x faster cache hits) **Result**: Single-region databases feel globally distributed. --- ## Setup Steps ### Prerequisites - Cloudflare account with Workers access - PostgreSQL (v9.0-17.x) or MySQL (v5.7-8.x) database - Database accessible via public internet (TLS/SSL required) or private network (Cloudflare Tunnel) - **April 2025**: Available on Free plan (10 configs) and Paid plan (25 configs) ### Connection String Formats ```bash # PostgreSQL postgres://user:password@host:5432/database postgres://user:password@host:5432/database?sslmode=require # MySQL mysql://user:password@host:3306/database # URL-encode special chars: p@ssw$rd → p%40ssw%24rd ``` --- ## Connection Patterns ### Single Connection (pg.Client) ```typescript const client = new Client({ connectionString: env.HYPERDRIVE.connectionString }); await client.connect(); const result = await client.query('SELECT ...'); ctx.waitUntil(client.end()); // CRITICAL: Non-blocking cleanup ``` **Use for**: Simple queries, single query per request ### Connection Pool (pg.Pool) ```typescript const pool = new Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 // CRITICAL: Workers limit is 6 connections (July 2025: configurable ~20 Free, ~100 Paid) }); const [result1, result2] = await Promise.all([ pool.query('SELECT ...'), pool.query('SELECT ...') ]); ctx.waitUntil(pool.end()); ``` **Use for**: Parallel queries in single request ### Connection Cleanup Rule **ALWAYS use `ctx.waitUntil(client.end())`** - non-blocking cleanup after response sent **NEVER use `await client.end()`** - blocks response, adds latency --- ## ORM Integration ### Drizzle ORM ```typescript import { drizzle } from "drizzle-orm/postgres-js"; import postgres from "postgres"; const sql = postgres(env.HYPERDRIVE.connectionString, { max: 5 }); const db = drizzle(sql); const allUsers = await db.select().from(users); ctx.waitUntil(sql.end()); ``` ### Prisma ORM ```typescript import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "@prisma/client"; import { Pool } from "pg"; const pool = new Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 }); const adapter = new PrismaPg(pool); const prisma = new PrismaClient({ adapter }); const users = await prisma.user.findMany(); ctx.waitUntil(pool.end()); ``` **Note**: Prisma requires driver adapters (`@prisma/adapter-pg`). --- ## Local Development **Option 1: Environment Variable (Recommended)** ```bash export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://user:password@localhost:5432/local_db" npx wrangler dev ``` Safe to commit config, no credentials in wrangler.jsonc. **Option 2: localConnectionString in wrangler.jsonc** ```jsonc { "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "prod-id", "localConnectionString": "postgres://..." }] } ``` ⚠️ Don't commit credentials to version control. **Option 3: Remote Development** ```bash npx wrangler dev --remote # ⚠️ Uses PRODUCTION database ``` --- ## Query Caching **Cached**: SELECT (non-mutating queries) **NOT Cached**: INSERT, UPDATE, DELETE, volatile functions (LASTVAL, LAST_INSERT_ID) **May 2025**: 5x faster cache hits via regional prepared statement caching. **Critical for postgres.js:** ```typescript const sql = postgres(env.HYPERDRIVE.connectionString, { prepare: true // REQUIRED for caching }); ``` **Check cache status:** ```typescript response.headers.get('cf-cache-status'); // HIT, MISS, BYPASS, EXPIRED ``` --- ## TLS/SSL Configuration **SSL Modes**: `require` (default), `verify-ca` (verify CA), `verify-full` (verify CA + hostname) **Server Certificates (verify-ca/verify-full):** ```bash npx wrangler cert upload certificate-authority --ca-cert root-ca.pem --name my-ca-cert npx wrangler hyperdrive create my-db --connect
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.