Cloudflare Workers let you run code at the edge in response to events—ideal for building custom APIs, serverless functions, and microservices with low latency and automatic scaling. OceanBase Cloud is MySQL-compatible, so you can connect from Workers over TCP or through Cloudflare Hyperdrive.
This guide walks you through creating a Cloudflare Workers app and connecting it to your OceanBase Cloud database so it can read and write data.
Note
We recommend using Cloudflare Hyperdrive to connect to your OceanBase database. Hyperdrive gives you better performance and keeps the connection between your Worker and OceanBase secure. If you connect directly to OceanBase without Hyperdrive, the MySQL driver may rely on Node.js APIs that are not supported in the Workers runtime for secure connections, which can cause the connection to fail.
Prerequisites
- You have an OceanBase Cloud account and have created a transactional instance and a MySQL-compatible tenant. For details, see Create a cluster instance and Create a tenant.
- You have created a database and an account with read and write permissions. For details, see Create an account and Create a database (MySQL only).
- You have the Project Admin or Instance Admin role so you can manage instances in the project. If not, ask your organization admin to grant the required permissions.
- You have a Cloudflare account.
- You have Node.js 16.17.0 or later installed (required by the Wrangler CLI).
Step 1: Get your database connection details
Log in to the OceanBase Cloud console. On the instance list, expand the target transactional instance, then under the target tenant click Connect > Get Connection String.
In the dialog, choose Public Network.
On the Connect via Public Network page, complete the following to generate a connection string:
(Optional) If the tenant does not yet have a public endpoint, under Step 1: Get Public Endpoint, click Get Public Endpoint. If one already exists, skip this step. Then click Next Step.
Under Step 2: Security Settings, do the following, then click Next Step:
Add IP Address(es) to Allowlist: Click Add, choose Allow All IP Addresses (Workers run on Cloudflare’s edge and need open access), then click OK.
Download Certificate: Click Download CA Certificate to download the certificate and complete verification.
Under Step 3: Access Database, select the database and account you created in the prerequisites, and choose MySQL CLI as the connection method. Copy the connection string for use when configuring Hyperdrive and DATABASE_URL later.
Step 2: Install and configure Wrangler
Wrangler is Cloudflare's official CLI for Workers. Use it to create, build, preview, and deploy your Workers.
Install Wrangler
npm install -g wrangler
Set environment variables
Create an API token in the Cloudflare dashboard:
- Click Create Token.
- Use the Edit Cloudflare Workers template and add Hyperdrive permissions.
- Copy the generated API token.
- Open Workers & Pages and note your Account ID and Subdomain.
In your local terminal, set these environment variables (replace the placeholders with your values):
export CLOUDFLARE_API_TOKEN="your-api-token-here" export CLOUDFLARE_ACCOUNT_ID="your-account-id"
Create a Worker project
Run the following to create a Worker project named
oceanbase-tutorial:wrangler init oceanbase-tutorialWhen prompted, choose:
Option Choice What would you like to start with? Hello World example Which template would you like to use? Worker only Which language do you want to use? TypeScript Do you want to use git for version control? Yes Do you want to deploy your application? No Go into the new project directory:
cd oceanbase-tutorial
Step 3: Set the DATABASE_URL secret
The format for DATABASE_URL is: mysql://username:password@host:port/database_name. Use the connection details you copied in Step 1 to build this string.
From the project root, run:
wrangler secret put DATABASE_URL
Enter your DATABASE_URL when prompted. On success you will see:
✨ Success! Uploaded secret DATABASE_URL
Step 4: Create a Hyperdrive config and bind it to your Worker
Create the Hyperdrive config
Create a Hyperdrive config using your OceanBase connection string in the form: mysql://username:password@hostname:port/database_name.
npx wrangler hyperdrive create oceanbase-hyperdrive --connection-string="mysql://username:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
Replace username, password, HOSTNAME_OR_IP_ADDRESS, PORT, and database_name with the values from Step 1. The command prints the Hyperdrive ID, keep it for the next step.
Bind Hyperdrive in your Wrangler config
Add a Hyperdrive binding in your project's wrangler.jsonc or wrangler.toml, and set YOUR_Hyperdrive_ID to the ID from the previous step.
Using
wrangler.jsonc:{ "$schema": "node_modules/wrangler/config-schema.json", "name": "oceanbase-tutorial", "main": "src/index.ts", "compatibility_date": "2024-09-23", "compatibility_flags": [ "nodejs_compat" ], "observability": { "enabled": true }, "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "YOUR_Hyperdrive_ID" } ] }Using
wrangler.toml:name = "oceanbase-tutorial" main = "src/index.ts" compatibility_date = "2024-09-23" compatibility_flags = ["nodejs_compat"] [observability] enabled = true [[hyperdrive]] binding = "HYPERDRIVE" id = "YOUR_Hyperdrive_ID"
Step 5: Install dependencies and add Worker code
Install the mysql2 driver
You need mysql2 v3.13.0 or later. From the project root, run one of:
npm i mysql2@">=3.13.0"
# or
yarn add mysql2@">=3.13.0"
# or
pnpm add mysql2@">=3.13.0"
Add the Worker entry code
Edit src/index.ts to connect to OceanBase via the Hyperdrive binding and run a simple query to verify connectivity:
// Requires mysql2 v3.13.0 or later
import { createConnection } from "mysql2/promise";
export interface Env {
HYPERDRIVE: {
host: string;
user: string;
password: string;
database: string;
port: number;
};
}
export default {
async fetch(request: Request, env: Env, ctx: { waitUntil: (promise: Promise<any>) => void }): Promise<Response> {
// Create a connection using the credentials provided by Hyperdrive (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 for mysql2 compatibility with the Workers runtime.
disableEval: true,
});
try {
const [results, fields] = await connection.query("SHOW TABLES;");
// Close the connection after sending the response, before the Worker terminates.
ctx.waitUntil(connection.end());
return Response.json({ results, fields });
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : "Unknown error" },
{ status: 500 }
);
}
},
} satisfies ExportedHandler<Env>;
Note
Hyperdrive requires mysql2 version 3.13.0 or higher, and you must set disableEval: true for compatibility with the Workers runtime.
Step 6: Deploy and test your Worker
Deploy the Worker
From the project root, run:
wrangler deploy
When deployment succeeds, you get a URL for your Worker (for example, https://oceanbase-tutorial.<your-subdomain>.workers.dev).
Test the Worker
Use curl to send a GET request and confirm that the Worker returns the result of SHOW TABLES from OceanBase:
curl "https://oceanbase-tutorial.<your-subdomain>.workers.dev"
If the response JSON includes results and fields with no errors, your Worker is successfully connected to OceanBase Cloud.