Skip to main content
Cloudflare Workers is a serverless platform that allows you to run your code at the edge, close to your users. Hyperdrive accelerates queries you make to existing databases.
Already created a PlanetScale Postgres database? Jump straight to integration instructions.
We’ll cover:
  • Creating a new Postgres database
  • Cluster configuration options
  • Connecting to your database

Prerequisites

Before you begin, make sure you have a PlanetScale account. After you create an account, you’ll be prompted to create a new organization, which is essentially a container for your databases, settings, and members. After creating your organization, it’s important to understand the relationship between databases, branches, and clusters.
  • Database: Your overall project (e.g., “my-ecommerce-app”)
  • Branch: Isolated database deployments that provide you with separate environments for development and testing, as well as restoring from backups - learn more about branching
  • Cluster: The underlying compute and storage infrastructure that powers each branch
PlanetScale Postgres clusters use real Postgres in a high-availability architecture with one primary and two replicas.

Create a new database

Step 1: Navigate to database creation

1
Log in to your PlanetScale dashboard
2
Select your organization from the dropdown
3
Click “New database” button or navigate to /new

Step 2: Choose database engine

1
On the database creation form, you’ll see two engine options:
  • Vitess (MySQL-compatible)
  • Postgres (PostgreSQL-compatible)
2
Select Postgres to create a PostgreSQL database

Step 3: Configure your database cluster

1
Database name: Enter a unique name for your database
2
Region: Choose the primary region where your database will be hosted
This “name” is referenced in the PlanetScale Dashboard and APIs and not created as a logical database inside of Postgres.
3
Cluster configuration: Select your preferred cluster size and CPU architecture

Step 4: Create the database cluster

1
Review your configuration settings
2
Click “Create database” to provision your Postgres database
3
Your database will be created with a main branch by default

What happens during creation

When you create a Postgres database cluster, PlanetScale automatically:
  • Provisions a PostgreSQL cluster in your selected region
  • Creates the initial main branch
  • Prepopulates Postgres with required default databases
  • Sets up monitoring and metrics collection
  • Configures backup and high availability settings

Create credentials and connect

In this section you’ll create the “Default role” in your PlanetScale dashboard to create connection credentials for your database branch.
The “Default role” is meant purely for administrative purposes. You can only create one and it has significant privileges for your database cluster and you should treat these credentials carefully. After completing this quickstart, it is strongly recommended that you create another role for your application use-cases.
Database dashboard
1
Navigate to your database in the PlanetScale dashboard
2
Click on the “Connect” button in the top right
3
Select “Default role”
4
Click “Create default role”. A new default role is created for your database branch.
5
Record the “Host”, “Username”, and “Password” for the “Default role” someplace secure.Create a new role
6
You can generate connection strings under “How are you connecting?” for major languages, frameworks, and tools.Connection stringsYour connection details will include:
  • Host: the DNS name of your database endpoint
  • Username: automatically formatted for routing to the correct branch
  • Password: A securely generated password
  • Database: postgres (default database)
  • Port: 5432 (standard PostgreSQL port) or 6432 (for using PgBouncer)
Passwords are shown only once. If you lose your record of the password, you must reset the password.

Integrate with Cloudflare Workers

Don’t have a Workers project yet? Create a Workers project from the Postgres template.

Step 1: Create a Hyperdrive connection

You can automatically create a connection from the PlanetScale dashboard when creating a new role. Alternatively, create a Hyperdrive connection by running the wrangler command below:
  • Replace the --connection-string placeholders with your database credentials
  • Replace the <hyperdrive-name> placeholder with a name for your Hyperdrive connection
Terminal
npx wrangler hyperdrive create <hyperdrive-name> --connection-string="postgresql://<username>:<password>@<host>:<port>/<database>?sslmode=verify-full"
Choose the appropriate port for your use case. Learn more about Direct vs PgBouncer connections.

PgBouncer

Port 6432 enables a lightweight connection pooler for PostgreSQL. This facilitates better performance when there are many simultaneous connections.

Direct

Port 5432 connects directly to PostgreSQL. Total connections are limited by your cluster’s max_connections setting.
Both connection types will disconnect when your database restarts or handles a failover scenario.
If successful, the command will output your new Hyperdrive configuration, for example:
Terminal
{
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<your-hyperdrive-id-here>"
    }
  ]
}

Step 2: Add Hyperdrive to your Wrangler configuration file

Specify the Hyperdrive resource ID and the binding name to connect to Hyperdrive from your Worker.
wrangler.jsonc
{
  // Add this section
  "compatibility_flags": [
    "nodejs_compat"
  ],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      // 👇 Update this with your Hyperdrive ID
      "id": "<your-hyperdrive-id-here>",

      // Optional. Can be used to connect to a local database for local development
      "localConnectionString": "postgresql://user:password@localhost:5432/databasename"
    }
  ]
}

Step 3: Create a database connection

Update your Worker code to connect to Hyperdrive.
src/index.ts
import { Client } from 'pg'

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    // Hyperdrive provides a unique generated connection string to connect to
    // your database via Hyperdrive that can be used with your existing tools
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    })

    try {
      await client.connect()

      // Sample query
      const result = await client.query('SELECT * from pg_tables')

      return Response.json({ result: result.rows })
    } catch (e) {
      return Response.json({ error: e instanceof Error ? e.message : e }, { status: 500 })
    } finally {
      // Close the client after the response is returned
      ctx.waitUntil(client.end())
    }
  }
}
Run the following to locally develop and test your Worker.
Terminal
npx wrangler dev
For more information on using Cloudflare Workers and Hyperdrive, refer to the Cloudflare documentation.

Need help?

Get help from the PlanetScale Support team, or join our GitHub discussion board to see how others are using PlanetScale.