Receber por email
← Voltar para o catálogo

cloudflare-hyperdrive

Complete knowledge domain for Cloudflare Hyperdrive - connecting Cloudflare Workers to existing PostgreSQL and MySQL databases with global connection pooling, query caching, and reduced latency. Use when: connecting Workers to existing databases, migrating PostgreSQL/MySQL to Cloudflare, setting up connection pooling, configuring Hyperdrive bindings, using node-postgres/postgres.js/mysql2 drivers,

15estrelas
Atualizado há 11 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add jackspace/ClaudeSkillz

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/cloudflare-hyperdrive/svg)](https://www.skillteca.com.br/skills/cloudflare-hyperdrive)

Skills relacionadas

Ver todas de Dados e Análise →

Alerta por categoria

Receba novas skills de Dados e Análise toda segunda

1 email curto, só com as skills novas de Dados e Análise. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

Cloudflare Hyperdrive

Status: Production Ready ✅ Last Updated: 2025-10-22 Dependencies: cloudflare-worker-base (recommended for Worker setup) Latest Versions: wrangler@4.43.0+, pg@8.13.0+, postgres@3.4.5+, mysql2@3.13.0+

Quick Start (5 Minutes)

1. Create Hyperdrive Configuration

# For PostgreSQL
npx wrangler hyperdrive create my-postgres-db \
  --connection-string="postgres://user:password@db-host.cloud:5432/database"

# For MySQL
npx wrangler hyperdrive create my-mysql-db \
  --connection-string="mysql://user:password@db-host.cloud: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:
  2. TCP handshake (1 round trip)
  3. TLS negotiation (3 round trips)
  4. Database authentication (3 round trips)
  5. Total: 7 round trips before you can even send a query
  1. 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:mypassword@db.example.com:5432/mydb"

# MySQL connection string format:
# mysql://username:password@hostname:port/database_name

npx wrangler hyperdrive create my-hyperdrive \
  --connection-string="mysql://myuser:mypassword@db.example.com:3306/mydb"

Option B: Cloudflare Dashboard

  1. Go to Hyperdrive Dashboard
  2. Click Create Configuration
  3. Enter connection details:
  4. Name: my-hyperdrive
  5. Protocol: PostgreSQL or MySQL
  6. Host: db.example.com
  7. Port: 5432 (PostgreSQL) or 3306 (MySQL)
  8. Database: mydb
  9. Username: myuser
  10. Password: mypassword
  11. Click Create

Connection String Formats:

# PostgreSQL (standard)
postgres://user:password@host:5432/database

# PostgreSQL with SSL mode
postgres://user:password@host:5432/database?sslmode=require

# MySQL
mysql://user:password@host:3306/database

# With special characters in password (URL encode)
postgres://user:p%40ssw%24rd@host:5432/database  # p@ssw$rd

Step 3: Configure Worker Bindings

Add Hyperdrive binding to wrangler.jsonc:

{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<your-hyperdrive-id-here>"
    }
  ]
}

Multiple Hyperdrive configs:

{
  "hyperdrive": [
    {
      "binding": "POSTGRES_DB",
      "id": "postgres-hyperdrive-id"
    },
    {
      "binding": "MYSQL_DB",
      "id": "mysql-hyperdrive-id"
    }
  ]
}

Access in Worker:

type Bindings = {
  POSTGRES_DB: Hyperdrive;
  MYSQL_DB: Hyperdrive;
};

export default {
  async fetch(request, env: Bindings, ctx) {
    // Access different databases
    const pgClient = new Client({ connectionString: env.POSTGRES_DB.connectionString });
    const mysqlConn = await createConnection({ host: env.MYSQL_DB.host, ... });
  }
};

Step 4: Install Database Driver

PostgreSQL Drivers:

# Option 1: node-postgres (pg) - Most popular
npm install pg
npm install @types/pg  # TypeScript types

# Option 2: postgres.js - Modern, faster (minimum v3.4.5)
npm install postgres@^3.4.5

MySQL Drivers:

# mysql2 (minimum v3.13.0)
npm install mysql2

Driver Comparison:

| Driver | Database | Pros | Cons | Min Version | |--------|----------|------|------|-------------| | pg | PostgreSQL | Most popular, stable, well-documented | Slightly slower than postgres.js | 8.13.0+ | | postgres | PostgreSQL | Faster, modern API, streaming support | Newer (less community examples) | 3.4.5+ | | mysql2 | MySQL | Promises, prepared statements, fast | Requires disableEval: true for Workers | 3.13.0+ |

Step 5: Use Driver in Worker

PostgreSQL with pg (Client):

import { Client } from "pg";

export default {
  async fetch(request: Request, env: { HYPERDRIVE: Hyperdrive }, ctx: ExecutionContext) {
    // Create client for this request
  
Compartilhar X LinkedIn