How to Connect Next.js to a Remote MySQL Database
Next.js is the most popular React framework for building fast web applications. Connecting it to a remote MySQL database like FreeDB allows you to build data-driven apps without managing your own server.
1. Set Up Your Environment Variables
First, create a .env.local file in your Next.js project root and add your FreeDB credentials:
DB_HOST=sql.freedb.tech
DB_USER=freedb_your_username
DB_PASSWORD=your_password
DB_NAME=freedb_your_database_name
2. Install MySQL Library
We recommend using the mysql2 package for its promise-based API and performance:
npm install mysql2
3. Create a Database Utility
Create a file at lib/db.js to handle the connection pool:
import mysql from 'mysql2/promise';
export async function query({ query, values = [] }) {
const dbconnection = await mysql.createConnection({
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
try {
const [results] = await dbconnection.execute(query, values);
dbconnection.end();
return results;
} catch (error) {
throw Error(error.message);
}
}
4. Use in a Server Component (Next.js 13+)
In your app/page.js, you can now fetch data directly on the server:
import { query } from '../lib/db';
export default async function Page() {
const products = await query({
query: "SELECT * FROM products LIMIT 10",
values: [],
});
return (
<div>
<h1>Products from FreeDB</h1>
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
Why this is great for Next.js
By using FreeDB with Next.js Server Components, you can fetch data during the build process or on-demand without exposing your database credentials to the client browser. This is secure, fast, and perfect for prototypes and production-ready applications.