Now let’s connect your Express API to the MySQL database. Create a new file called src/database.ts in your project:
import "dotenv/config";
import mysql, { Pool } from "mysql2/promise";
// Create a connection pool to manage database connections
const pool: Pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
export { pool };
What this code does
import "dotenv/config"loads your environment variables.import mysql, { Pool }imports mysql2 and thePooltype for TypeScript.const pool: Poolexplicitly types the connection pool.mysql.createPool()creates a connection pool to your MySQL database.process.env.DB_HOSTetc. use your database credentials from the.envfile.- The pool automatically manages database connections for better performance.
TypeScript note
We import the Pool type to demonstrate TypeScript usage. Going forward, we’ll let TypeScript infer types to keep database code clean and focused on SQL concepts.
Why use a connection pool?
Instead of creating a new connection for every API request (which is slow), the pool maintains a set of reusable connections. This improves performance and handles connection cleanup automatically, so you don’t need to close connections on each request.