You're reading docs for Nextly Alpha. APIs may change between releases.

Database

MySQL

Set up Nextly with MySQL. Covers installation, connection strings, charset and collation, pool tuning, SSL, deadlock retry, migrations, and gaps versus PostgreSQL.

MySQL is supported. Use it when you already run MySQL or a MySQL-compatible cloud database. The adapter uses mysql2 and emulates features MySQL lacks (RETURNING, ILIKE) on top of the shared DrizzleAdapter core.

MySQL is second-class to PostgreSQL in Nextly. Some features Nextly relies on -- savepoints for nested transactions, JSONB, array types, native ILIKE, native RETURNING -- either don't exist or are emulated. PostgreSQL is the recommended production database; pick MySQL only if it is already part of your stack. See the feature comparison.

Minimum version: MySQL 8.0. Older real MySQL hard-fails at connect with a clear upgrade pointer. MySQL-compatible variants (MariaDB, TiDB, Aurora MySQL, PlanetScale, Vitess) warn and proceed -- see database support for the variant policy.

Installation

Install the adapter alongside the mysql2 driver:

pnpm add @nextlyhq/adapter-mysql mysql2
npm install @nextlyhq/adapter-mysql mysql2
yarn add @nextlyhq/adapter-mysql mysql2
bun add @nextlyhq/adapter-mysql mysql2

Configuration

Set DB_DIALECT=mysql and DATABASE_URL in your environment.

.env
DB_DIALECT=mysql
DATABASE_URL=mysql://nextly:nextly@localhost:3306/nextly_dev

Programmatic usage

src/db.ts
import { createMySqlAdapter } from "@nextlyhq/adapter-mysql";

const adapter = createMySqlAdapter({
  url: process.env.DATABASE_URL!,
});

await adapter.connect();

Or pass discrete fields:

const adapter = createMySqlAdapter({
  host: "localhost",
  port: 3306,
  database: "nextly_dev",
  user: "nextly",
  password: "nextly",
});

Connection string

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

For example:

.env
DATABASE_URL=mysql://nextly:nextly@localhost:3306/nextly_dev

Charset and collation

MySQL's default utf8 is a 3-byte subset of UTF-8 that doesn't store emoji or many CJK characters. Use utf8mb4 for everything Nextly stores. The adapter does not force a charset by default -- set it on the connection:

const adapter = createMySqlAdapter({
  url: process.env.DATABASE_URL!,
  charset: "utf8mb4",
});

For a freshly created database, configure the server-level defaults too:

CREATE DATABASE nextly_dev
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

The Docker setup at the repo root already runs MySQL with --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci.

Connection pool

The adapter uses mysql2's built-in pool. Defaults:

OptionDefaultDescription
pool.max10 (3 on Vercel)Maps to mysql2's connectionLimit. Maximum simultaneous connections.
pool.min0Connections kept open however long they are idle. Like PostgreSQL's pool.min, it is how many of the connections the pool has opened it keeps: the pool does not open connections ahead of demand to reach it.
pool.idleTimeoutMs30000 (5000 on Vercel)How long a connection above pool.min may stay idle before it is closed, checked once a second. 0 keeps every idle connection open.
pool.connectionTimeoutMs15000 (5000 on Vercel; 45000 during next build, everywhere)Also DB_POOL_CONNECTION_TIMEOUT. How long a request waits in the queue while every connection is in use. Past it the request fails as DATABASE_BUSY (503, Retry-After: 5), and the adapter logs a warning naming the wait; 0 leaves that wait unbounded. Also the time a new connection gets to open (mysql2 connectTimeout): one that cannot open in time fails as a connection error, not as busy.
const adapter = createMySqlAdapter({
  url: process.env.DATABASE_URL!,
  pool: {
    max: 20,
    idleTimeoutMs: 30000,
    connectionTimeoutMs: 10000,
  },
});

mysql2's own idle closing cannot keep a minimum: it closes every connection idle past its idleTimeout, and only when maxIdle is set below connectionLimit. So the adapter sets maxIdle equal to connectionLimit, which keeps mysql2 from closing idle connections by itself, and closes them itself: past pool.idleTimeoutMs, least recently used first, down to pool.min. These are the settings and the defaults the PostgreSQL adapter uses on a server, so pool and the DB_POOL_* variables mean the same pool on both.

Needs the release after 0.0.2-alpha.78. Before it the pool closed no idle connection outside Vercel and ignored pool.min, so a server kept every connection it had opened. To keep connections open as before, set pool.min to the pool's maximum (DB_POOL_MIN=10 with the default maximum, or the same value as DB_POOL_MAX), or set pool.idleTimeoutMs: 0 in code.

The pool is configured with waitForConnections: true: a request that finds every connection in use waits in the queue for a free one, for at most pool.connectionTimeoutMs. The queue has no length limit (queueLimit: 0); each wait in it is bounded instead. A connection that frees up after its request gave up goes straight back to the pool.

On Vercel

On Vercel (where VERCEL is set) the pool defaults to max: 3, min: 0, idleTimeoutMs: 5000 and connectionTimeoutMs: 5000, so every connection idle for 5 seconds is closed, and a request that finds all three held fails as DATABASE_BUSY after 5 seconds. A Vercel function instance is suspended between requests and keeps the connections it holds open while suspended, so a small pool that closes idle connections quickly keeps a small database within its connection limit. Each setting you give, in pool or as a DB_POOL_* env var, replaces only its own default.

When @vercel/functions is installed in the app, the adapter also hands its pool to attachDatabasePool, which keeps an instance alive until its idle connections have closed. It is an optional peer dependency: without it the adapter logs one warning at connect. See Database connections on Vercel.

During next build

While next build runs (NEXT_PHASE is phase-production-build), a request waits up to 45 seconds in the queue for a connection, on Vercel and off it, and a new connection gets as long to open. Next.js prerenders several pages at once in each build worker on one pool, so reads queue, and a build answers no visitor who would rather be told the database is busy. The pool's size and idle timeout stay those of where the build runs: 3 connections on Vercel. pool.connectionTimeoutMs or DB_POOL_CONNECTION_TIMEOUT replaces the wait here too; keep it under 60000, the time Next.js gives a page. A database that refuses connections still fails the build at once. See The pool during next build.

SSL / TLS

System health on the dashboard reads whether the connection is actually encrypted; see Encrypted connections.

For production, enable SSL:

const adapter = createMySqlAdapter({
  url: process.env.DATABASE_URL!,
  ssl: { rejectUnauthorized: true, ca: process.env.CA_CERT },
});

ssl: true enables SSL with driver defaults; ssl: false (or omitted) disables it. The full SslConfig shape (rejectUnauthorized, ca, cert, key) is the same as the PostgreSQL adapter.

MySQL-specific options

OptionTypeDefaultDescription
charsetstring(driver default)Connection charset. Set to utf8mb4 for full Unicode.
timezonestring'local'Timezone for date handling, e.g. '+00:00'.
multipleStatementsbooleanfalseAllow multiple statements per query. Off for SQL-injection safety; the adapter forces false.
dateStringsbooleanfalseReturn dates as strings instead of Date objects. The adapter forces false.
queryTimeoutMsnumber (ms)15000Default for the adapter's internal timeout helpers.
const adapter = createMySqlAdapter({
  url: process.env.DATABASE_URL!,
  charset: "utf8mb4",
  timezone: "+00:00",
});

Differences from PostgreSQL

The adapter handles each of these automatically, but they are worth knowing:

  • No RETURNING. After INSERT, the adapter issues a follow-up SELECT (using insertId for auto-increment, otherwise filtering by inserted column values) to return the row. Bulk inserts return rows by reading result.insertId..result.insertId + affectedRows - 1.
  • Nested transactions join flat. A transaction() called inside another's work runs as part of it, on its connection, with no savepoint of its own: its failure fails the whole transaction, even when the outer work catches it. supportsSavepoints is therefore false. The transaction context's own savepoint, rollbackToSavepoint and releaseSavepoint do set InnoDB savepoints, which Nextly uses to undo one failed item of a batch create and keep the rest. On TiDB, which refuses SAVEPOINT before 6.2 and in a pessimistic transaction unless tidb_constraint_check_in_place_pessimistic is on, the three methods are undefined, and a batch item that fails after its row is written aborts the whole batch instead.
  • No native ILIKE. Case-insensitive search is rewritten to LOWER(column) LIKE LOWER(value).
  • No JSONB. MySQL has a native JSON type but no JSONB-style binary-indexed variant.
  • No array types. Store arrays as JSON.
  • Upsert needs a table with one unique key. MySQL has no ON CONFLICT (columns): ON DUPLICATE KEY UPDATE fires on a collision with any unique key, so it can't be held to the columns you name. The adapter's upsert therefore accepts a table only when its conflict columns are its one unique key besides the primary key. On any other table, it refuses before writing and names the other unique keys. There, insert and update inside a transaction() instead. On a table it accepts, upsert means what it does on PostgreSQL and SQLite: the row is inserted, or the existing row with that key is updated (or kept, when no column is left to update), and the stored row is returned. The conflict columns must be given values, and a conflict is resolved on the values you give: a BEFORE INSERT trigger that rewrites the key onto another row's value is refused as a unique violation rather than resolved onto that row.
  • Backtick identifiers. MySQL uses `name` instead of "name".
  • ? placeholders. MySQL uses positional ? instead of $1, $2.

See the full feature matrix on the database overview.

Deadlock retry

Transaction failures with MySQL error code 1213 (ER_LOCK_DEADLOCK) automatically retry when you opt in via transaction() options:

await adapter.transaction(
  async tx => {
    await tx.insert("orders", orderData);
    await tx.update("inventory", stockUpdate, where);
  },
  {
    retryCount: 3,
    retryDelayMs: 100, // exponential backoff: 100ms, 200ms, 300ms
  }
);

Lock-wait timeouts (error 1205) and other failures are not retried -- they surface immediately so callers can decide what to do.

Migrations

MySQL uses the same forward-only migration CLI as the other dialects:

pnpm nextly migrate:create --name=add-posts-table
pnpm nextly migrate:status
pnpm nextly migrate:check
pnpm nextly migrate
pnpm nextly migrate:fresh   # destructive, local-dev only

Rolling back. nextly migrate:down rolls back the most recently applied migration using its -- DOWN section; there is no migrate:rollback. For anything else, write a new corrective migration. See production migrations.

Local development with Docker

The repo's docker-compose.yml includes a MySQL profile. Start it with:

docker compose --profile mysql up -d mysql

That uses the same image and config as below. To run MySQL standalone:

docker-compose.yml
services:
  mysql:
    image: mysql:8.0
    restart: unless-stopped
    environment:
      MYSQL_ROOT_PASSWORD: dev_password
      MYSQL_DATABASE: nextly_dev
      MYSQL_USER: nextly
      MYSQL_PASSWORD: dev_password
    command: >
      --default-authentication-plugin=mysql_native_password
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_unicode_ci
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql

volumes:
  mysql_data:
docker compose up -d mysql
.env
DB_DIALECT=mysql
DATABASE_URL=mysql://nextly:dev_password@localhost:3306/nextly_dev

Capabilities

The adapter reports the following capabilities at runtime:

{
  dialect: "mysql",
  supportsJsonb: false,
  supportsJson: true,
  supportsArrays: false,
  supportsGeneratedColumns: true,
  supportsFts: true,
  supportsIlike: false,
  supportsReturning: false,
  supportsSavepoints: false,
  supportsOnConflict: true,
  maxParamsPerQuery: 65535,
  maxIdentifierLength: 64,
}

Next steps