Pular para o conteúdo

mysql

Atualizado em Ver como Markdown

The mysql package is a MySQL driver for Node.js. This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.

Install the mysql driver:


								
									
									npm
									 i mysql
								
							

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 and pass the Hyperdrive parameters:

import { createConnection } from "mysql";

export default {
	async fetch(request, env, ctx): Promise<Response> {
		const result = await new Promise<any>((resolve) => {
			// Create a connection using the mysql driver with the Hyperdrive credentials (only accessible from your Worker).
			const connection = createConnection({
				host: env.HYPERDRIVE.host,
				user: env.HYPERDRIVE.user,
				password: env.HYPERDRIVE.password,
				database: env.HYPERDRIVE.database,
				port: env.HYPERDRIVE.port,
			});

			connection.connect((error: { message: string }) => {
				if (error) {
					throw new Error(error.message);
				}

				// Sample query
				connection.query("SHOW tables;", [], (error, rows, fields) => {
					resolve({ fields, rows });
				});
			});
		});

		// Return result  as JSON
		return new Response(JSON.stringify(result), {
			headers: {
				"Content-Type": "application/json",
			},
		});
	},
} satisfies ExportedHandler<Env>;