TiDB Cloud Serverless Driver Node.js Tutorial
April 22, 2026 ยท View on GitHub
This tutorial describes how to use TiDB Cloud serverless driver in a local Node.js project.
Note:
- In addition to {{{ .starter }}} instances, the steps in this document also work with {{{ .essential }}} instances.
- To learn how to use TiDB Cloud serverless driver with Cloudflare Workers, Vercel Edge Functions, and Netlify Edge Functions, check out our Insights into Automotive Sales and the sample repository.
Before you begin
To complete this step-by-step tutorial, you need the following:
- Node.js >= 18.0.0.
- npm or your preferred package manager.
- A {{{ .starter }}} instance. If you don't have any, you can create a {{{ .starter }}} instance.
Step 1. Create a local Node.js project
-
Create a project named
node-example:mkdir node-example cd node-example -
Install the TiDB Cloud serverless driver using npm or your preferred package manager.
The following command takes installation with npm as an example. Executing this command will create a
node_modulesdirectory and apackage.jsonfile in your project directory.npm install @tidbcloud/serverless
Step 2. Use the serverless driver
The serverless driver supports both CommonJS and ES modules. The following steps take the usage of the ES module as an example.
-
On the overview page of your {{{ .starter }}} instance, click Connect in the upper-right corner, and then get the connection string for your database from the displayed dialog. The connection string looks like this:
mysql://[username]:[password]@[host]/[database] -
In the
package.jsonfile, specify the ES module by addingtype: "module".For example:
{ "type": "module", "dependencies": { "@tidbcloud/serverless": "^0.0.7", } } -
Create a file named
index.jsin your project directory and add the following code:import { connect } from '@tidbcloud/serverless' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) // replace with your {{{ .starter }}} instance information console.log(await conn.execute("show tables")) -
Run your project with the following command:
node index.js
Compatibility with earlier versions of Node.js
If you are using Node.js earlier than 18.0.0, which does not have a global fetch function, you can take the following steps to get fetch:
-
Install a package that provides
fetch, such asundici:npm install undici -
Pass the
fetchfunction to theconnectfunction:import { connect } from '@tidbcloud/serverless' import { fetch } from 'undici' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]',fetch})