PlanetScale
PlanetScale ↗ is a database platform that provides MySQL-compatible and PostgreSQL databases, making them more scalable, easier and safer to manage.
To connect to PlanetScale using Hyperdrive, follow these steps:
You can connect Hyperdrive to any existing PlanetScale MySQL-compatible database by creating a new user and fetching your database connection string.
- Go to the PlanetScale dashboard ↗ and select the database you wish to connect to.
- Click Connect. Enter
hyperdrive-useras the password name (or your preferred name) and configure the permissions as desired. Select Create password. Note the username and password as they will not be displayed again. - Select Other as your language or framework. Note down the database host, database name, database username, and password. You will need these to create a database configuration in Hyperdrive.
With the host, database name, username and password, you can now create a Hyperdrive database configuration.
To configure Hyperdrive, you will need:
- The IP address (or hostname) and port of your database.
- The database username (for example,
hyperdrive-demo) you configured in a previous step. - The password associated with that username.
- The name of the database you want Hyperdrive to connect to. For example,
mysql.
Hyperdrive accepts the combination of these parameters in the common connection string format used by database drivers:
mysql://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_nameMost database providers will provide a connection string you can copy-and-paste directly into Hyperdrive.
To create a Hyperdrive configuration with the Wrangler CLI, open your terminal and run the following command.
- Replace <NAME_OF_HYPERDRIVE_CONFIG> with a name for your Hyperdrive configuration and paste the connection string provided from your database host, or,
- Replace
user,password,HOSTNAME_OR_IP_ADDRESS,port, anddatabase_nameplaceholders with those specific to your database:
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="mysql://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"This command outputs a binding for the Wrangler configuration file:
{ "name": "hyperdrive-example", "main": "src/index.ts", "compatibility_date": "2024-08-21", "compatibility_flags": [ "nodejs_compat" ], "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>" } ]}name = "hyperdrive-example"main = "src/index.ts"compatibility_date = "2024-08-21"compatibility_flags = ["nodejs_compat"]
# Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.[[hyperdrive]]binding = "HYPERDRIVE"id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"Install the mysql2 ↗ driver:
npm i mysql2@>3.13.0yarn add mysql2@>3.13.0pnpm add mysql2@>3.13.0Add the required Node.js compatibility flags and Hyperdrive binding to your wrangler.jsonc file:
{ "compatibility_flags": [ "nodejs_compat" ], "compatibility_date": "2024-09-23", "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<your-hyperdrive-id-here>" } ]}# required for database drivers to functioncompatibility_flags = ["nodejs_compat"]compatibility_date = "2024-09-23"
[[hyperdrive]]binding = "HYPERDRIVE"id = "<your-hyperdrive-id-here>"Create a new connection instance and pass the Hyperdrive parameters:
// mysql2 v3.13.0 or later is requiredimport { createConnection } from "mysql2/promise";
export default { async fetch(request, env, ctx): Promise<Response> { // Create a connection using the mysql2 driver with the Hyperdrive credentials (only accessible from your Worker). const connection = await createConnection({ host: env.HYPERDRIVE.host, user: env.HYPERDRIVE.user, password: env.HYPERDRIVE.password, database: env.HYPERDRIVE.database, port: env.HYPERDRIVE.port,
// Required to enable mysql2 compatibility for Workers disableEval: true, });
try { // Sample query const [results, fields] = await connection.query("SHOW tables;");
// Clean up the client after the response is returned, before the Worker is killed ctx.waitUntil(connection.end());
// Return result rows as JSON return Response.json({ results, fields }); } catch (e) { console.error(e); } },} satisfies ExportedHandler<Env>;- Learn more about How Hyperdrive Works.
- Refer to the troubleshooting guide to debug common issues.
- Understand more about other storage options available to Cloudflare Workers.
To set up an integration with PlanetScale:
-
You need to have an existing PlanetScale database to connect to. Create a PlanetScale database ↗ or import an existing database to PlanetScale ↗.
-
From the PlanetScale web console ↗, create a
productstable with the following query:CREATE TABLE products (id int NOT NULL AUTO_INCREMENT PRIMARY KEY,name varchar(255) NOT NULL,image_url varchar(255),category_id INT,KEY category_id_idx (category_id)); -
Insert some data in your newly created table. Run the following command to add a product and category to your table:
INSERT INTO products (name, image_url, category_id)VALUES ('Ballpoint pen', 'https://example.com/500x500', '1'); -
Configure the PlanetScale database credentials in your Worker:
You need to add your PlanetScale database credentials as secrets to your Worker. Get your connection details from the PlanetScale Dashboard ↗ by creating a connection string, then add them as secrets using Wrangler:
Terminal window # Add the database host as a secretnpx wrangler secret put DATABASE_HOST# When prompted, paste your PlanetScale host# Add the database username as a secretnpx wrangler secret put DATABASE_USERNAME# When prompted, paste your PlanetScale username# Add the database password as a secretnpx wrangler secret put DATABASE_PASSWORD# When prompted, paste your PlanetScale password -
In your Worker, install the
@planetscale/databasedriver to connect to your PlanetScale database and start manipulating data:Terminal window npm i @planetscale/databaseTerminal window yarn add @planetscale/databaseTerminal window pnpm add @planetscale/database -
The following example shows how to make a query to your PlanetScale database in a Worker. The credentials needed to connect to PlanetScale have been added as secrets to your Worker.
JavaScript import { connect } from "@planetscale/database";export default {async fetch(request, env) {const config = {host: env.DATABASE_HOST,username: env.DATABASE_USERNAME,password: env.DATABASE_PASSWORD,// see https://github.com/cloudflare/workerd/issues/698fetch: (url, init) => {delete init["cache"];return fetch(url, init);},};const conn = connect(config);const data = await conn.execute("SELECT * FROM products;");return Response.json(data.rows, {status: 200,});},};
To learn more about PlanetScale, refer to PlanetScale's official documentation ↗.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark