Getting started (9)·续
To install pg, ensure you are in the hyperdrive-tutorial directory. Open your terminal and run the following command:
npmyarnpnpmbun
# This should install v8.16.3 or later
npm i pg
# This should install v8.16.3 or later
yarn add pg
# This should install v8.16.3 or later
pnpm add pg
# This should install v8.16.3 or later
bun add pg
If you are using TypeScript, you should also install the type definitions for pg:
npmyarnpnpmbun
# This should install v8.13.0 or later
npm i -D @types/pg
# This should install v8.13.0 or later
yarn add -D @types/pg
# This should install v8.13.0 or later
pnpm add -D @types/pg
# This should install v8.13.0 or later
bun add -d @types/pg
With the driver installed, you can now create a Worker script that queries your database.
To connect to your database, you will need a database driver which allows you to authenticate and query your database. For this tutorial, you will use mysql2 ↗︎, one of the most widely used MySQL drivers.
To install mysql2, ensure you are in the hyperdrive-tutorial directory. Open your terminal and run the following command:
npmyarnpnpmbun
# This should install v3.13.0 or later
npm i mysql2
# This should install v3.13.0 or later
yarn add mysql2
# This should install v3.13.0 or later
pnpm add mysql2
# This should install v3.13.0 or later
bun add mysql2
With the driver installed, you can now create a Worker script that queries your database.
Write a Worker
After you have set up your database, you will run a SQL query from within your Worker.
Go to your hyperdrive-tutorial Worker and open the index.ts file.
The index.ts file is where you configure your Worker's interactions with Hyperdrive.
Populate your index.ts file with the following code:
// pg 8.16.3 or later is recommended
import { Client } from "pg";
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 new client on each request. Hyperdrive maintains the underlying
// database connection pool, so creating a new client is fast.
const sql = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
// Connect to the database
await sql.connect();
// Sample query
const results = await sql.query(`SELECT * FROM pg_tables`);
// Return result rows as JSON
return Response.json(results.rows);
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;
Upon receiving a request, the code above does the following:
- Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
- Initiates a query via
await sql.query()that outputs all tables (user and system created) in the database (as an example query). - Returns the response as JSON to the client. Hyperdrive automatically cleans up the client connection when the request ends, and keeps the underlying database connection open in its pool for reuse.
After you have set up your database, you will run a SQL query from within your Worker.
Go to your hyperdrive-tutorial Worker and open the index.ts file.
The index.ts file is where you configure your Worker's interactions with Hyperdrive.
Populate your index.ts file with the following code:
// mysql2 v3.13.0 or later is required
import { createConnection } from "mysql2/promise";
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 new connection on each request. Hyperdrive maintains the underlying
// database connection pool, so creating a new connection is fast.
const connection = await createConnection({
host: env.HYPERDRIVE.host,
user: env.HYPERDRIVE.user,
password: env.HYPERDRIVE.password,
database: env.HYPERDRIVE.database,
port: env.HYPERDRIVE.port,
// The following line is needed for mysql2 compatibility with Workers
// mysql2 uses eval() to optimize result parsing for rows with > 100 columns
// Configure mysql2 to use static parsing instead of eval() parsing with disableEval
disableEval: true,
});
try {
// Sample query
const [results, fields] = await connection.query("SHOW tables;");
// Return result rows as JSON
return new Response(JSON.stringify({ results, fields }), {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;
Upon receiving a request, the code above does the following:
- Creates a new database client configured to connect to your database via Hyperdrive, using the Hyperdrive connection string.
- Initiates a query via
await connection.querythat outputs all tables (user and system created) in the database (as an example query). - Returns the response as JSON to the client. Hyperdrive automatically cleans up the client connection when the request ends, and keeps the underlying database connection open in its pool for reuse.
Run in development mode (optional)
You can test your Worker locally before deploying by running wrangler dev. This runs your Worker code on your machine while connecting to your database.
The localConnectionString field works with both local and remote databases and allows you to connect directly to your database from your Worker project running locally. You must specify the SSL/TLS mode if required (sslmode=require for Postgres, sslMode=REQUIRED for MySQL).
To connect to a database during local development, configure localConnectionString in your wrangler.jsonc:
{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "your-hyperdrive-id",
"localConnectionString": "postgres://user:password@your-database-host:5432/database",
},
],
}
Or set an environment variable:
export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://user:password@your-database-host:5432/database"
Then start local development:
npx wrangler dev
Note
When using wrangler dev with localConnectionString or CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE, Hyperdrive caching does not take effect locally.
Alternatively, you can run wrangler dev --remote to test against your deployed Hyperdrive configuration with caching enabled, but this runs your entire Worker in Cloudflare's network instead of locally.
Learn more about local development with Hyperdrive.
6. Deploy your Worker
You can now deploy your Worker to make your project accessible on the Internet. To deploy your Worker, run:
npx wrangler deploy
# Outputs: https://hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev
You can now visit the URL for your newly created project to query your live database.
For example, if the URL of your new Worker is hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev, accessing https://hyperdrive-tutorial.<YOUR_SUBDOMAIN>.workers.dev/ will send a request to your Worker that queries your database directly.
By finishing this tutorial, you have created a Hyperdrive configuration, a Worker to access that database and deployed your project globally.
Reduce latency with Placement
If your Worker makes multiple sequential queries per request, use Placement to run your Worker close to your database. Each query adds round-trip latency: 20-30ms from a distant region, or 1-3ms when placed nearby. Multiple queries compound this difference.
If your Worker makes only one query per request, placement does not improve end-to-end latency. The total round-trip time is the same whether it happens near the user or near the database.
wrangler.jsoncjsonc
{
"placement": {
"region": "aws:us-east-1", // Match your database region, for example "gcp:us-east4" or "azure:eastus"
},
}
Next steps
- Learn more about how Hyperdrive works.
- How to configure query caching.
- Troubleshooting common issues when connecting a database to Hyperdrive.
If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the Cloudflare Developers community on Discord ↗︎.
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/hyperdrive/get-started/#page","headline":"Getting started","description":"Create your first Hyperdrive configuration and connect a Cloudflare Worker to your database.","url":"https://developers.cloudflare.com/hyperdrive/get-started/","inLanguage":"en","image":"https://developers.cloudflare.com/hyperdrive/get-started/og.png?v=94c405fe5d773d8e","dateModified":"2026-10-21","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Learn how Cloudflare partners with PlanetScale to provide managed Postgres and MySQL databases for Workers applications with Hyperdrive acceleration. title: PlanetScale Postgres & MySQL image: https://developers.cloudflare.com/hyperdrive/planetscale/og.png?v=e4d0acbf14eeaf5b
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/hyperdrive/llms.txt
Use this file to discover all available pages before exploring further.
Docs