Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

cloudflare-hyperdrive

БесплатноБез исполняемых скриптовНе проверен

Covers Cloudflare Hyperdrive, which connects Cloudflare Workers to existing PostgreSQL and MySQL databases with global connection pooling and query caching…

jackspaceот jackspace★ 16 звёзд на GitHub15 установок в других каталогах

Об этом скилле

Cloudflare Hyperdrive

Status: Production Ready ✅ Last Updated: 2025-10-22 Dependencies: cloudflare-worker-base (recommended for Worker setup) Latest Versions: [email protected]+, [email protected]+, [email protected]+, [email protected]+


Quick Start (5 Minutes)

1. Create Hyperdrive Configuration

# 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:

{
  "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

# 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):

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:

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

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

The Problem

Connecting to traditional databases from Cloudflare's 300+ global locations presents challenges:

  1. High Latency - Multiple round trips for each connection:

    • TCP handshake (1 round trip)
    • TLS negotiation (3 round trips)
    • Database authentication (3 round trips)
    • Total: 7 round trips before you can even send a query
  2. Connection Limits - Traditional databases handle limited concurrent connections, easily exhausted by distributed traffic

The Solution

Hyperdrive solves these problems by:

  1. Edge Connection Setup - Connection handshake happens near your Worker (low latency)
  2. Connection Pooling - Pool near your database reuses connections (eliminates round trips)
  3. Query Caching - Popular queries cached at the edge (reduces database load)

Result: Single-region databases feel globally distributed.


Complete Setup Process

Step 1: Prerequisites

You need:

  • Cloudflare account with Workers access
  • Existing PostgreSQL (v9.0-17.x) or MySQL (v5.7-8.x) database
  • Database accessible via:
    • Public internet (with TLS/SSL enabled), OR
    • Private network (via Cloudflare Tunnel)

Important: Hyperdrive requires TLS/SSL. Ensure your database has encryption enabled.


Step 2: Create Hyperdrive Configuration

Option A: Wrangler CLI (Recommended)

# PostgreSQL connection string format:
# postgres://username:password@hostname:port/database_name

npx wrangler hyperdrive create my-hyperdrive \
  --connection-string="postgres://myuser:[email protected]:5432/mydb"

# MySQL connection string format:
# mysql
Полный SKILL.md на GitHub

Установить cloudflare-hyperdrive в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

README.mdSKILL.json

FAQ

Что делает скилл cloudflare-hyperdrive?

Covers Cloudflare Hyperdrive, which connects Cloudflare Workers to existing PostgreSQL and MySQL databases with global connection pooling and query caching: creating configs with wrangler hyperdrive create, wrangler.jsonc bindings, the required nodejs_compat flag, driver setup for node-postgres (pg), postgres.js and mysql2, Drizzle ORM and Prisma integration, local development, and caching and TLS options. Use when giving Workers access to RDS, Aurora, Neon or Supabase databases, setting up connection pooling or a hybrid architecture, or debugging errors such as Failed to acquire a connection from the pool, TLS not supported by the database, connection refused, missing nodejs_compat, or Code generation from strings disallowed.

Как установить скилл cloudflare-hyperdrive?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл cloudflare-hyperdrive запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить cloudflare-hyperdrive с