本页还没有译文
本页 37 段还没译成简体中文,下面显示的是英文原文。Connect to a MySQL database with Cloudflare Workers
还没翻译译自英文(developers.cloudflare.com)本页 37 段都还没译
In this tutorial, you will learn how to create a Cloudflare Workers application and connect it to a MySQL database using TCP Sockets and Hyperdrive. The Workers application you create in this tutorial will interact with a product database inside of MySQL.
Note
We recommend using Hyperdrive to connect to your MySQL database. Hyperdrive provides optimal performance and will ensure secure connectivity between your Worker and your MySQL database.
When connecting directly to your MySQL database (without Hyperdrive), the MySQL drivers rely on unsupported Node.js APIs to create secure connections, which prevents connections.
Prerequisites
To continue:
-
Sign up for a Cloudflare account if you have not already.
-
Install
npm. -
Install
Node.js.Use Vite+ (
vp env) to install and manage Node.js versions.For supported Node.js versions, refer to the Wrangler system requirements.
-
Make sure you have access to a MySQL database.
1. Create a Worker application
First, use the create-cloudflare CLI to create a new Worker application. To do this, open a terminal window and run the following command:
npm create cloudflare@latest -- mysql-tutorialyarn create cloudflare mysql-tutorialpnpm create cloudflare@latest mysql-tutorialThis will prompt you to install the create-cloudflare package and lead you through a setup wizard.
For setup, select the following options:
- For What would you like to start with?, choose
Hello World example. - For Which template would you like to use?, choose
Worker only. - For Which language do you want to use?, choose
TypeScript. - For Do you want to use git for version control?, choose
Yes. - For Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?, choose
Yes. - For Do you want to deploy your application?, choose
No(we will be making some changes before deploying).
If you choose to deploy, you will be asked to authenticate (if not logged in already), and your project will be deployed. If you deploy, you can still modify your Worker code and deploy again at the end of this tutorial.
Now, move into the newly created directory:
cd mysql-tutorial2. Enable Node.js compatibility
Node.js compatibility is required for database drivers, including mysql2, and needs to be configured for your Workers project.
For compatibility dates of 2026-08-04 or later, Workers and Pages projects enable both nodejs_compat and nodejs_compat_v2 by default. Built-in runtime APIs and polyfills are available without additional configuration. These flags are not used for these compatibility dates. Existing projects do not need to remove them when updating their compatibility date.
If your compatibility date is before 2026-08-04, add the nodejs_compat compatibility flag to your Wrangler configuration file to opt in:
{
"compatibility_flags": [
"nodejs_compat"
]
}compatibility_flags = [ "nodejs_compat" ]
To turn off Node.js compatibility completely for a compatibility date of 2026-08-04 or later, remove the positive flags if present. Then add both no_nodejs_compat and no_nodejs_compat_v2. For configuration examples, refer to the Node.js compatibility flag.
3. Create a Hyperdrive configuration
Create a Hyperdrive configuration using the connection string for your MySQL database.
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="mysql://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"This command outputs the Hyperdrive configuration id that will be used for your Hyperdrive binding. Set up your binding by specifying the id in the Wrangler file.
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "hyperdrive-example",
"main": "src/index.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-02",
"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"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-02"
compatibility_flags = [ "nodejs_compat" ]
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
4. Query your database from your Worker
Install the mysql2 driver:
npm i mysql2@>3.13.0yarn add mysql2@>3.13.0pnpm add mysql2@>3.13.0bun add mysql2@>3.13.0Note
mysql2 v3.13.0 or later is required
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-11-02",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-11-02"
[[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>;Note
The minimum version of mysql2 required for Hyperdrive is 3.13.0.
5. Deploy your Worker
Run the following command to deploy your Worker:
npx wrangler deployYour application is now live and accessible at <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev.
Next steps
To build more with databases and Workers, refer to Tutorials and explore the Databases documentation.
If you have any questions, need assistance, or would like to share your project, join the Cloudflare Developer community on Discord to connect with fellow developers and the Cloudflare team.