OceanBase
English日本語简体中文
Docs Home
Products
Integrations
Release Notes

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog ServiceOceanBase DataPilot

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog ServiceOceanBase DataPilot
OceanBase DatabaseOceanBase Cloud ToolsConnectors and MiddlewareLifecycle Support Policy

OceanBase Cloud

  • Overview
  • Schema evolution
    • Liquibase
    • Flyway
  • Data ingestion
    • Canal
    • dbt
    • Debezium
    • Flink
    • Glue
    • Informatica Cloud
    • Kafka
    • Maxwell
    • SeaTunnel
    • DataWorks
    • NiFi
  • SQL development
    • DataGrip
    • DBeaver
    • Navicat
    • TablePlus
  • Orchestration
    • DolphinScheduler
    • Linkis
    • Airflow
  • Visualization
    • Grafana
    • Power BI
    • Quick BI
    • Superset
    • Tableau
  • Observability
    • Datadog
    • Prometheus
  • Database management
    • Bytebase
  • AI
    • LlamaIndex
    • Dify
    • LangChain
    • Tongyi Qianwen
    • OpenAI
    • n8n
    • Trae
    • SpringAI
    • Cline
    • Cursor
    • Continue
    • Toolbox
    • CamelAI
    • Firecrawl
    • Hugging Face
    • Ollama
    • Google Gemini
    • Cloudflare Workers AI
    • Qoder
    • OpenCode
    • Claude Code
    • GitHub Copilot
    • Codex
    • Jina AI
    • Augment Code
    • Claude Code
    • Kiro
  • Development tools
    • Cloudflare Workers
    • Vercel

Download PDF

Document Feedback
  1. Documentation Center
  2. OceanBase Cloud

Connect to OceanBase Cloud from Cloudflare Workers

Last Updated:2026-09-04 07:03:30

Prerequisites
Step 1: Get your database connection details
Step 2: Install and configure Wrangler
Install Wrangler
Set environment variables
Create a Worker project
Step 3: Set the DATABASE_URL secret
Step 4: Create a Hyperdrive config and bind it to your Worker
Create the Hyperdrive config
Bind Hyperdrive in your Wrangler config
Step 5: Install dependencies and add Worker code
Install the mysql2 driver
Add the Worker entry code
Step 6: Deploy and test your Worker
Deploy the Worker
Test the Worker

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

  1. 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.

  2. In the dialog, choose Public Network.

  3. On the Connect via Public Network page, complete the following to generate a connection string:

    1. (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.

    2. 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.

    3. 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

  1. Create an API token in the Cloudflare dashboard:

    1. Click Create Token.
    2. Use the Edit Cloudflare Workers template and add Hyperdrive permissions.
    3. Copy the generated API token.
    4. Open Workers & Pages and note your Account ID and Subdomain.
  2. 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

  1. Run the following to create a Worker project named oceanbase-tutorial:

    wrangler init oceanbase-tutorial
    
  2. When 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
  3. 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.

Previous topic

Kiro
Last

Next topic

Vercel
Next
on this page
Prerequisites
Step 1: Get your database connection details
Step 2: Install and configure Wrangler
Install Wrangler
Set environment variables
Create a Worker project
Step 3: Set the DATABASE_URL secret
Step 4: Create a Hyperdrive config and bind it to your Worker
Create the Hyperdrive config
Bind Hyperdrive in your Wrangler config
Step 5: Install dependencies and add Worker code
Install the mysql2 driver
Add the Worker entry code
Step 6: Deploy and test your Worker
Deploy the Worker
Test the Worker