Pular para o conteúdo

PlanetScale

Atualizado em Ver como Markdown

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:

1. Allow Hyperdrive access

You can connect Hyperdrive to any existing PlanetScale MySQL-compatible database by creating a new user and fetching your database connection string.

PlanetScale Dashboard

  1. Go to the PlanetScale dashboard and select the database you wish to connect to.
  2. Click Connect. Enter hyperdrive-user as 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.
  3. 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.

2. Create a 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_name

Most 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, and database_name placeholders 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:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "hyperdrive-example",
	"main": "src/index.ts",
	// Set this to today's date
	"compatibility_date": "2026-07-20",
	"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>"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "hyperdrive-example"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-07-20"
compatibility_flags = [ "nodejs_compat" ]

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"

3. Use Hyperdrive from your Worker

Install the mysql2 driver:


								
									
									npm
									 i mysql2@>3.13.0
								
							

Add the required Node.js compatibility flags and Hyperdrive binding to your wrangler.jsonc file:

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-07-20",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-07-20"

[[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 required
import { createConnection } from "mysql2/promise";

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,

			// Required to enable mysql2 compatibility for Workers
			disableEval: true,
		});

		try {
			// Sample query
			const [results, fields] = await connection.query("SHOW tables;");

			// Return result rows as JSON
			return Response.json({ results, fields });
		} catch (e) {
			console.error(e);
			return Response.json(
				{ error: e instanceof Error ? e.message : e },
				{ status: 500 },
			);
		}
	},
} satisfies ExportedHandler<Env>;

Next steps

Set up an integration with PlanetScale

To set up an integration with PlanetScale:

  1. You need to have an existing PlanetScale database to connect to. Create a PlanetScale database or import an existing database to PlanetScale.

  2. From the PlanetScale web console, create a products table 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)
    );
  3. 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');
  4. 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:

    # Add the database host as a secret
    npx wrangler secret put DATABASE_HOST
    # When prompted, paste your PlanetScale host
    
    # Add the database username as a secret
    npx wrangler secret put DATABASE_USERNAME
    # When prompted, paste your PlanetScale username
    
    # Add the database password as a secret
    npx wrangler secret put DATABASE_PASSWORD
    # When prompted, paste your PlanetScale password
  5. In your Worker, install the @planetscale/database driver to connect to your PlanetScale database and start manipulating data:

    
    								
    									
    									npm
    									 i @planetscale/database
    								
    							
  6. 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.

    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/698
    			fetch: (url, init) => {
    				delete init["cache"];
    				return fetch(url, init);
    			},
    		};
    
    		const conn = connect(config);
    		const data = await conn.execute("SELECT * FROM products;");
    		return new Response(JSON.stringify(data.rows), {
    			status: 200,
    			headers: {
    				"Content-Type": "application/json",
    			},
    		});
    	},
    };

To learn more about PlanetScale, refer to PlanetScale's official documentation.