How do I connect an Express app to MySQL with DATABASE_URL?

Install express and mysql2, create a pool with mysql.createPool(process.env.DATABASE_URL) and query with ? parameters. The connection string lives in a local .env and is set by the environment in production, so the code never changes.

For an Express MySQL DATABASE_URL setup, install express and mysql2, create a pool with mysql.createPool(process.env.DATABASE_URL) and run your queries with pool.query using ? parameters. Locally, the connection string lives in a .env file you never commit. In production the environment sets it, so the code is identical in both cases.

This recipe uses Node.js with ES modules (ESM), Express and the promise-based version of the mysql2 driver. If you're new to the framework, first read what Express.js is and what it's for.

1. Install the dependencies

npm init -y
npm install express mysql2

To use import instead of require, add "type": "module" to your package.json.

2. Understand DATABASE_URL

mysql2 accepts a connection string in URI format:

mysql://user:password@host:port/database

An example with fictional data for your local machine would be mysql://dev:secreto123@localhost:3306/miapp. That string is for development only. In production you don't write it in the code, because the environment variable is provided by the platform where your app runs.

3. The complete code

Create a server.js file:

import express from 'express';
import mysql from 'mysql2/promise';

if (!process.env.DATABASE_URL) {
  throw new Error('Missing DATABASE_URL variable');
}

const pool = mysql.createPool(process.env.DATABASE_URL);
const app = express();
app.use(express.json());

// Health: checks that the database responds
app.get('/health', async (req, res) => {
  try {
    await pool.query('SELECT 1');
    res.json({ ok: true });
  } catch (err) {
    console.error(err);
    res.status(500).json({ ok: false });
  }
});

// Read a note with a parameter (prevents SQL injection)
app.get('/notas/:id', async (req, res) => {
  try {
    const [rows] = await pool.query(
      'SELECT id, titulo, creado_en FROM notas WHERE id = ?',
      [req.params.id]
    );
    if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
    res.json(rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Database error' });
  }
});

// Create a note from a JSON body
app.post('/notas', async (req, res) => {
  const { titulo } = req.body;
  if (!titulo) return res.status(400).json({ error: 'Missing titulo' });
  try {
    const [result] = await pool.query(
      'INSERT INTO notas (titulo) VALUES (?)',
      [titulo]
    );
    res.status(201).json({ id: result.insertId, titulo });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Database error' });
  }
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));

Some key points:

  • A pool instead of a single connection: the pool reuses connections and manages them for you, so you don't have to open and close a connection on every request.
  • ? parameters: never concatenate user data into the SQL, because mysql2 escapes the values you pass in the array.
  • try/catch in every route: if the database fails, you respond with a controlled error and the app doesn't crash.
  • process.env.PORT || 3000: in production the platform assigns the port, and locally port 3000 is used.

4. Create the table

The code doesn't create the table on its own. You run the migrations yourself, whether from a MySQL client, with your own script or with a migration tool. Here's a minimal example:

CREATE TABLE notas (
  id INT AUTO_INCREMENT PRIMARY KEY,
  titulo VARCHAR(200) NOT NULL,
  creado_en TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

5. Local development with .env

Create a .env file in the project root:

DATABASE_URL=mysql://dev:secreto123@localhost:3306/miapp

Add .env to your .gitignore so it never reaches GitHub. You have two options to load the file:

  1. With Node 20.6 or later you don't need to install anything else: node --env-file=.env server.js.
  2. With the dotenv package: run npm install dotenv and add import 'dotenv/config'; as the first line of server.js.

To test that everything works, open http://localhost:3000/health. It should respond {"ok":true}.

Common errors

  • Empty DATABASE_URL: the variable isn't defined because you didn't load the .env, you ran it from another folder or you misspelled the name. The check at the start of the code warns you instead of failing later.
  • Password with special characters: symbols like @, #, / or : break the URL. Encode the password with encodeURIComponent('p@ss#1'), which returns p%40ss%231, and use the result inside the string.
  • Not closing connections: if you open a connection with createConnection on every request and don't close it, you end up exhausting the available connections. The pool avoids this problem.
  • Wrong driver: a mysql:// string needs mysql2. If your AI installed pg (which is for PostgreSQL), the connection won't work.

On Dongee Live

Dongee Live, Dongee's hosting for AI-built apps, publishes apps made with AI (ChatGPT, Lovable, Bolt, v0, Claude Code, Codex, Cursor or VS Code). Each app comes with a MySQL database included, and its connection string is already in the DATABASE_URL variable. That's why the code in this recipe works without changes. Live supports Node.js 20, 22 and 24, as well as Express, Fastify, Koa and Hono. It also keeps the app running, restarts it if it crashes and issues HTTPS.

You have two ways to publish:

  • With the skill: in the Claude Code, Codex or Cursor terminal, run npx skills add dongeelive/skills -g -y and then tell your AI "publish". The upload limit this way is 100 MB.
  • Through GitHub: you connect the repository and every push publishes the app. The limit this way is 32 MB.

You can define your own environment variables, including on Live Free. The full step-by-step is in how to publish a Node.js app with MySQL from Claude Code or Cursor.

Honest comparison: when Live fits and when it doesn't

Your appDongee Live?Alternative
Express + MySQLYes, the database is included—
Express + PostgreSQL or MongoDB on the same serverNo, Live only offers MySQLAn external service such as Supabase, or Dongee Cloud
Backend in Python or with DockerNoDongee Cloud
PHP or WordPressNoDongee's cPanel hosting

If your project comes from Lovable, first check whether it really uses a backend: is your Lovable app static or does it need a server?

Live Free costs 0 USD and includes 1 app, 1 MySQL database and 1 email account. Live Pro costs 15 USD/month and includes 3 apps and your own domain with SSL.

Frequently asked questions

Do I have to change the code when moving from local to production?

No. The code always reads process.env.DATABASE_URL. Locally the variable comes from your .env, and in production the environment sets it.

Why use mysql2/promise and not mysql?

Because mysql2 supports async/await natively and accepts the URI connection string directly in createPool.

Who creates my app's tables?

You do. The MySQL database comes included in DATABASE_URL, and the tables and migrations are part of your project: run them with your own script or with a migration tool.

Can I use Supabase instead of the included MySQL database?

Yes. An app on Live can connect to external services such as Supabase. In that case, you store its credentials in your own environment variables.

Does it work if my app uses Next.js with SSR?

Yes. Live supports Next.js in standalone mode with SSR, and the MySQL connection works the same as in this recipe.

Summary

To connect Express to MySQL you need a pool created from DATABASE_URL, parameterized queries, error handling and a /health route. If your database is MySQL, you can take the same code to Dongee Live without changes. If your app depends on another database, on Python or on Docker, choose another option.

Comenta lo que quieras

Unete a la charla
Solo ingresa tu email