title | summary |
---|---|
Connect to TiDB with mysql2 in Next.js |
This article describes how to build a CRUD application using TiDB and mysql2 in Next.js and provides a simple example code snippet. |
TiDB is a MySQL-compatible database, and mysql2 is a popular open-source driver for Node.js.
In this tutorial, you can learn how to use TiDB and mysql2 in Next.js to accomplish the following tasks:
- Set up your environment.
- Connect to your TiDB cluster using mysql2.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.
Note
This tutorial works with TiDB Serverless and TiDB Self-Hosted.
To complete this tutorial, you need:
- Node.js 18 or later.
- Git.
- A TiDB cluster.
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
This section demonstrates how to run the sample application code and connect to TiDB.
Note
For complete code snippets and running instructions, refer to the tidb-nextjs-vercel-quickstart GitHub repository.
Run the following commands in your terminal window to clone the sample code repository:
git clone git@github.com:tidb-samples/tidb-nextjs-vercel-quickstart.git
cd tidb-nextjs-vercel-quickstart
Run the following command to install the required packages (including mysql2
) for the sample app:
npm install
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
-
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
-
Click Connect in the upper right corner. A connection dialog is displayed.
-
Ensure the configurations in the connection dialog match your operating environment.
- Endpoint Type is set to
Public
- Branch is set to
main
- Connect With is set to
General
- Operating System matches your environment.
Note
In Node.js applications, you do not have to provide an SSL CA certificate, because Node.js uses the built-in Mozilla CA certificate by default when establishing the TLS (SSL) connection.
- Endpoint Type is set to
-
Click Generate Password to create a random password.
Tip
If you have created a password before, you can either use the original password or click Reset Password to generate a new one.
-
Run the following command to copy
.env.example
and rename it to.env
:# Linux cp .env.example .env
# Windows Copy-Item ".env.example" -Destination ".env"
-
Copy and paste the corresponding connection string into the
.env
file. The example result is as follows:TIDB_HOST='{gateway-region}.aws.tidbcloud.com' TIDB_PORT='4000' TIDB_USER='{prefix}.root' TIDB_PASSWORD='{password}' TIDB_DB_NAME='test'
Replace the placeholders in
{}
with the values obtained in the connection dialog. -
Save the
.env
file.
-
Run the following command to copy
.env.example
and rename it to.env
:# Linux cp .env.example .env
# Windows Copy-Item ".env.example" -Destination ".env"
-
Copy and paste the corresponding connection string into the
.env
file. The example result is as follows:TIDB_HOST='{tidb_server_host}' TIDB_PORT='4000' TIDB_USER='root' TIDB_PASSWORD='{password}' TIDB_DB_NAME='test'
Replace the placeholders in
{}
with the values obtained in the Connect window. If you are running TiDB locally, the default host address is127.0.0.1
, and the password is empty. -
Save the
.env
file.
-
Start the application:
npm run dev
-
Open your browser and visit
http://localhost:3000
. (Check your terminal for the actual port number, and the default is3000
.) -
Click RUN SQL to execute the sample code.
-
Check the output in the terminal. If the output is similar to the following, the connection is successful:
{ "results": [ { "Hello World": "Hello World" } ] }
You can refer to the following sample code snippets to complete your own application development.
For complete sample code and how to run it, check out the tidb-nextjs-vercel-quickstart repository.
The following code establish a connection to TiDB with options defined in the environment variables:
// src/lib/tidb.js
import mysql from 'mysql2';
let pool = null;
export function connect() {
return mysql.createPool({
host: process.env.TIDB_HOST, // TiDB host, for example: {gateway-region}.aws.tidbcloud.com
port: process.env.TIDB_PORT || 4000, // TiDB port, default: 4000
user: process.env.TIDB_USER, // TiDB user, for example: {prefix}.root
password: process.env.TIDB_PASSWORD, // The password of TiDB user.
database: process.env.TIDB_DATABASE || 'test', // TiDB database name, default: test
ssl: {
minVersion: 'TLSv1.2',
rejectUnauthorized: true,
},
connectionLimit: 1, // Setting connectionLimit to "1" in a serverless function environment optimizes resource usage, reduces costs, ensures connection stability, and enables seamless scalability.
maxIdle: 1, // max idle connections, the default value is the same as `connectionLimit`
enableKeepAlive: true,
});
}
export function getPool() {
if (!pool) {
pool = createPool();
}
return pool;
}
The following query creates a single Player
record and returns a ResultSetHeader
object:
const [rsh] = await pool.query('INSERT INTO players (coins, goods) VALUES (?, ?);', [100, 100]);
console.log(rsh.insertId);
For more information, refer to Insert data.
The following query returns a single Player
record by ID 1
:
const [rows] = await pool.query('SELECT id, coins, goods FROM players WHERE id = ?;', [1]);
console.log(rows[0]);
For more information, refer to Query data.
The following query adds 50
coins and 50
goods to the Player
with ID 1
:
const [rsh] = await pool.query(
'UPDATE players SET coins = coins + ?, goods = goods + ? WHERE id = ?;',
[50, 50, 1]
);
console.log(rsh.affectedRows);
For more information, refer to Update data.
The following query deletes the Player
record with ID 1
:
const [rsh] = await pool.query('DELETE FROM players WHERE id = ?;', [1]);
console.log(rsh.affectedRows);
For more information, refer to Delete data.
- Using connection pools to manage database connections can reduce the performance overhead caused by frequently establishing and destroying connections.
- To avoid SQL injection, it is recommended to use prepared statements.
- In scenarios where there are not many complex SQL statements involved, using ORM frameworks like Sequelize, TypeORM, or Prisma can greatly improve development efficiency.
- For more details on how to build a complex application with ORM and Next.js, see our Bookshop Demo.
- Learn more usage of node-mysql2 driver from the documentation of node-mysql2.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as Insert data, Update data, Delete data, Single table reading, Transactions, and SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Ask questions on the Discord, or create a support ticket.
Ask questions on the Discord, or create a support ticket.