Skip to content
Derar Sattouf

Next.js and MySQL in 2026: Connection Pool, Queries and Server Actions

Next.js & frontend

Next.js and MySQL in 2026: Connection Pool, Queries and Server Actions

People search for "Next.js vs MySQL", but they are not alternatives. Next.js is a React framework that renders pages and runs server code. MySQL is a database that stores your data. A Next.js app reads and writes MySQL from its server code, the same way an Express or Laravel app would. The real question is how to connect the two well in the App Router, where the old answer ("write an API route and fetch it") is no longer the best one.

The short answer:

  • One mysql2 pool per server process, created in a module marked server-only, and kept on globalThis so hot reload in development does not open a new pool on every save.
  • Read in Server Components. Call the database directly from the component. No API route, no fetch to your own server.
  • Write in Server Actions. Check who the user is, validate the form, run a parameterized query, then expire the cache with updateTag.
  • Use a transaction on one connection when two writes must succeed or fail together.
  • Keep the pool small on serverless hosts, run on the Node.js runtime, and on Vercel attach the pool with attachDatabasePool.

The code below is written against the Next.js 16.4 docs and mysql2/promise. If you need a plain REST API for a mobile app or another service, the route handler version is in ToDo CRUD API with MySQL in Next.js, Nuxt.js and SvelteKit.

What this guide uses

PieceChoiceWhy
FrameworkNext.js 16, App RouterServer Components and Server Actions are where database code belongs now
Drivermysql2 (promise API)The standard MySQL driver for Node.js, with pooling and prepared statements built in
DatabaseMySQL 8.4 LTS, or MariaDB, PlanetScale, Aurora MySQLMySQL 8.0 reached end of life in April 2026; 8.4 is the long-term release
RuntimeNode.js (the default)mysql2 opens TCP sockets, which the Edge runtime does not have

The example is a small inventory app: a list of products, a form to add one, and an order action that takes stock off a product.

CREATE TABLE products (
  id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name        VARCHAR(120) NOT NULL UNIQUE,
  price_cents INT UNSIGNED NOT NULL,
  stock       INT UNSIGNED NOT NULL DEFAULT 0,
  created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  product_id  INT UNSIGNED NOT NULL,
  user_id     INT UNSIGNED NOT NULL,
  quantity    INT UNSIGNED NOT NULL,
  created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (product_id) REFERENCES products (id)
);

Prices are stored as whole cents in an INT. A DECIMAL column also works, but mysql2 returns DECIMAL values as strings by default so that no precision is lost, and that surprises people the first time they add two prices together.

Create a database user for the app that can only SELECT, INSERT, UPDATE and DELETE on this schema, and put its connection string in .env.local:

DATABASE_URL="mysql://shop_app:change-me@127.0.0.1:3306/shop"

Step 1: one pool, in a server-only module

Install the driver and the server-only marker:

npm install mysql2 server-only

Then create the pool once:

// lib/db.ts
import "server-only";
import mysql from "mysql2/promise";

const globalForDb = globalThis as unknown as { pool?: mysql.Pool };

export const pool =
  globalForDb.pool ??
  mysql.createPool({
    uri: process.env.DATABASE_URL,
    connectionLimit: 5, // per server process, see "Connection limits" below
    maxIdle: 5,
    idleTimeout: 60_000, // close connections idle for a minute
    enableKeepAlive: true,
  });

if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;

Three things are going on here:

  • import "server-only" turns an accidental import from a Client Component into a build error. Without it, the mistake shows up as a confusing "Module not found: Can't resolve 'net'" error, because the bundler tries to pack mysql2 for the browser.
  • The globalThis cache matters in development. Every time you save a file, Next.js re-runs changed modules; without the cache each save creates a new pool, the old ones keep their connections open, and after a while MySQL answers with "Too many connections".
  • connectionLimit is the most connections this pool will ever open. The default is 10. On a single long-running server you can raise it; on serverless keep it low, for reasons covered below.

pool.query() and pool.execute() both check out a connection, run one statement and give the connection back, so you rarely need to handle connections yourself. The exception is transactions, in step 4.

query or execute?

Both are safe from SQL injection as long as values go in ? placeholders and never into the SQL string. The difference:

  • execute uses a server-side prepared statement, which mysql2 caches per connection. Good for statements you run often.
  • query escapes the values on the client and sends plain SQL. It accepts things execute does not, such as IN (?) with an array.

One trap with execute: passing a JavaScript number to LIMIT ? can fail with "Incorrect arguments to mysqld_stmt_execute" on MySQL 8. Use query for those statements or pass the limit as a string.

Step 2: read in Server Components

A Server Component runs only on the server, so it can call the database directly. Put the queries in their own module so pages stay readable and every query has one home:

// lib/products.ts
import "server-only";
import type { RowDataPacket } from "mysql2";
import { cacheLife, cacheTag } from "next/cache";
import { pool } from "./db";

export type Product = {
  id: number;
  name: string;
  priceCents: number;
  stock: number;
};

type ProductRow = RowDataPacket & {
  id: number;
  name: string;
  price_cents: number;
  stock: number;
};

const toProduct = (row: ProductRow): Product => ({
  id: row.id,
  name: row.name,
  priceCents: row.price_cents,
  stock: row.stock,
});

export async function getProducts(): Promise<Product[]> {
  "use cache";
  cacheLife("hours");
  cacheTag("products");

  const [rows] = await pool.query<ProductRow[]>(
    "SELECT id, name, price_cents, stock FROM products ORDER BY name",
  );
  return rows.map(toProduct);
}

Mapping each row to a plain Product object does two jobs. It turns snake_case columns into the names the rest of the app uses, and it makes sure what leaves the function is a plain, serializable object. That matters because a "use cache" result is stored and replayed, and anything you pass from a Server Component to a Client Component has to be serializable too.

The page then reads like any other async component:

// app/products/page.tsx
import { getProducts } from "@/lib/products";
import { NewProductForm } from "./new-product-form";

const price = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

export default async function ProductsPage() {
  const products = await getProducts();

  return (
    <main>
      <h1>Products</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            {product.name}: {price.format(product.priceCents / 100)} ({product.stock} in stock)
          </li>
        ))}
      </ul>
      <NewProductForm />
    </main>
  );
}

Cached or fresh on every request?

How this behaves depends on whether the app has Cache Components turned on (cacheComponents: true in next.config.ts). New apps from create-next-app have it on; apps upgraded from Next.js 14 or 15 often do not.

With Cache Components, you choose per query:

  • Add "use cache" with cacheLife and cacheTag, as above, for data that is the same for everyone and can be a little old: a product list, a menu, published articles. The result becomes part of the prerendered page and is refreshed on the schedule you set, or at once when a Server Action calls updateTag("products").
  • Leave "use cache" out for data that must be fresh on every request, and wrap the component that reads it in <Suspense> so the rest of the page is sent first. Without the boundary, the dev overlay flags the route as blocking.

One consequence of caching: a "use cache" function used on a static page runs during next build. The build machine then needs to reach the database. If your CI has no database access, the build fails with a connection error, and the fix is either to give the build a read-only connection or to not cache that query.

Without Cache Components (the previous model), there is a trap. A page that does not read cookies, headers or search params is prerendered at build time, and its database queries run then, once. The page shows the same rows until the next deploy. If a page must show live data, opt it out explicitly:

import { connection } from "next/server";

export default async function ProductsPage() {
  await connection(); // render this page per request, not at build time
  const products = await getProducts(); // in this model, without the "use cache" lines
  // ...
}

export const dynamic = "force-dynamic" does the same for the whole route. For data that can be cached in the previous model, wrap the query in unstable_cache with a tags option instead of "use cache".

If the same query runs twice in one request, for example in generateMetadata and in the page, wrap the uncached function in React's cache() so the database is hit once. The Server Components and caching guide goes deeper into use cache, cacheLife and request deduplication.

Step 3: write with Server Actions

A Server Action is an async function marked "use server" that a form can call directly. Next.js turns it into a POST endpoint, sends the form data, and returns the updated page in the same round trip.

That endpoint is public. Anyone can call it with a crafted request, whatever your UI shows or hides, so every action needs the same checks as an API route: who is calling, are they allowed, and is the input valid.

// app/products/actions.ts
"use server";

import { updateTag } from "next/cache";
import { pool } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth"; // your auth library's session helper

export type FormState = { error?: string; ok?: boolean };

function readNumber(formData: FormData, key: string): number | null {
  const raw = formData.get(key);
  if (typeof raw !== "string" || raw.trim() === "") return null;
  const value = Number(raw);
  return Number.isFinite(value) ? value : null;
}

export async function createProduct(_prev: FormState, formData: FormData): Promise<FormState> {
  const user = await getCurrentUser();
  if (!user?.isAdmin) return { error: "You are not allowed to add products." };

  const name = String(formData.get("name") ?? "").trim();
  const price = readNumber(formData, "price");
  const stock = readNumber(formData, "stock");

  if (name.length < 2 || name.length > 120) return { error: "Name must be 2 to 120 characters." };
  if (price === null || price < 0) return { error: "Enter a price of 0 or more." };
  if (stock === null || !Number.isInteger(stock) || stock < 0) return { error: "Stock must be a whole number." };

  try {
    await pool.execute(
      "INSERT INTO products (name, price_cents, stock) VALUES (?, ?, ?)",
      [name, Math.round(price * 100), stock],
    );
  } catch (error) {
    if ((error as { code?: string }).code === "ER_DUP_ENTRY") {
      return { error: "A product with that name already exists." };
    }
    console.error("createProduct failed", error);
    return { error: "The product could not be saved. Try again." };
  }

  updateTag("products");
  return { ok: true };
}

The details that matter:

  • Errors go back as state, not as thrown exceptions, for the cases the user can fix. A thrown error ends up in the nearest error.tsx, which is the wrong place for "that name is taken". The raw database error is logged on the server and never sent to the browser.
  • ER_DUP_ENTRY is the mysql2 error code for a unique key violation. Checking the code is more reliable than querying "does this name exist?" first, because two requests can both pass that check before either inserts.
  • updateTag("products") expires every cached result tagged products, so the list the user sees right after saving already contains the new row. It only works inside Server Actions. From a route handler or a webhook, use revalidateTag("products", "max"), which refreshes in the background instead.
  • Without Cache Components, there is no "use cache" tag to expire. Call revalidatePath("/products"), or refresh() from next/cache if the page is already dynamic, so the action's response carries the updated page.

The form is a small Client Component that uses useActionState for the pending flag and the error message:

// app/products/new-product-form.tsx
"use client";

import { useActionState } from "react";
import { createProduct, type FormState } from "./actions";

const initialState: FormState = {};

export function NewProductForm() {
  const [state, formAction, pending] = useActionState(createProduct, initialState);

  return (
    <form action={formAction}>
      <label>
        Name <input name="name" required minLength={2} maxLength={120} />
      </label>
      <label>
        Price <input name="price" type="number" step="0.01" min="0" required />
      </label>
      <label>
        Stock <input name="stock" type="number" step="1" min="0" required />
      </label>
      <button type="submit" disabled={pending}>
        {pending ? "Saving..." : "Add product"}
      </button>
      {state.error ? <p role="alert">{state.error}</p> : null}
      {state.ok ? <p role="status">Saved.</p> : null}
    </form>
  );
}

The required, min and maxLength attributes give quick feedback in the browser. They are a convenience, not a check: the action validates again, because a request does not have to come from this form. For optimistic updates and pending states across a whole page, see React 19 actions, forms and optimistic UI.

Updates and deletes: check ownership in the SQL

Never trust an id that comes from the browser on its own. A hidden <input name="id"> or an argument bound to the action can be changed to any value. Put the ownership rule in the WHERE clause and check how many rows changed:

// app/orders/actions.ts
"use server";

import type { ResultSetHeader } from "mysql2";
import { updateTag } from "next/cache";
import { pool } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";

export async function deleteOrder(orderId: number) {
  const user = await getCurrentUser();
  if (!user) return { error: "Sign in first." };
  if (!Number.isInteger(orderId) || orderId < 1) return { error: "Order not found." };

  const [result] = await pool.execute<ResultSetHeader>(
    "DELETE FROM orders WHERE id = ? AND user_id = ?",
    [orderId, user.id],
  );

  if (result.affectedRows === 0) return { error: "Order not found." };
  updateTag("orders");
  return { ok: true };
}

A Client Component calls it like any async function, for example from a button's click handler inside startTransition, and shows the returned error. The orderId argument travels through the browser, which is why the action checks it again. If someone sends another user's order id, the query matches nothing and they get "not found", which also avoids telling them that the order exists.

Step 4: transactions on one connection

Placing an order takes stock off a product and inserts an order row. If the second write fails, the first must be undone. That is a transaction, and a transaction has to run on one connection from start to finish. pool.query may pick a different connection for each call, so check one out yourself:

// lib/orders.ts
import "server-only";
import type { ResultSetHeader } from "mysql2";
import { pool } from "./db";

export class OutOfStockError extends Error {}

export async function placeOrder(userId: number, productId: number, quantity: number) {
  const conn = await pool.getConnection();
  try {
    await conn.beginTransaction();

    const [stock] = await conn.execute<ResultSetHeader>(
      "UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?",
      [quantity, productId, quantity],
    );
    if (stock.affectedRows !== 1) throw new OutOfStockError();

    const [order] = await conn.execute<ResultSetHeader>(
      "INSERT INTO orders (product_id, user_id, quantity) VALUES (?, ?, ?)",
      [productId, userId, quantity],
    );

    await conn.commit();
    return order.insertId;
  } catch (error) {
    await conn.rollback();
    throw error;
  } finally {
    conn.release();
  }
}
  • The stock check is inside the UPDATE (AND stock >= ?). Reading the stock first and updating it later leaves a gap where two buyers both see one item left. A conditional update is atomic, so only one of them gets affectedRows = 1. When you do need to read first, use SELECT ... FOR UPDATE inside the transaction to lock the row.
  • release() in finally returns the connection to the pool on every path. A connection that is never released is lost to the pool, and after connectionLimit of them every query waits forever.
  • Deadlocks happen under load, and MySQL resolves them by aborting one transaction with ER_LOCK_DEADLOCK. Retrying that transaction once is the standard response. Keep transactions short and touch tables in the same order everywhere to make deadlocks rare.

The Server Action wraps this with the usual checks and maps OutOfStockError to a message the user can act on, then calls updateTag("products") because the stock changed.

Step 5: connection limits on serverless

On a single server, one pool of 10 to 20 connections serves a lot of traffic. Serverless changes the arithmetic: every running instance has its own pool, so the number of open connections is the number of instances times connectionLimit. MySQL's default max_connections is 151. Twenty busy instances with the default pool of 10 can ask for 200.

What keeps that under control:

  • A small connectionLimit, such as 5, and an idleTimeout so idle connections close instead of waiting for MySQL's own timeout, which defaults to eight hours.
  • Not going down to one connection. A pool of one does not lower the total much, and it makes requests inside an instance wait for each other.
  • On Vercel, attach the pool so idle connections are closed before an instance is suspended. attachDatabasePool from @vercel/functions supports mysql2 pools:
// lib/db.ts, after creating the pool
import { attachDatabasePool } from "@vercel/functions";

attachDatabasePool(pool);
  • A connection proxy or an HTTP driver when the numbers still do not fit. Managed services offer proxies (RDS Proxy for Aurora and RDS, for example), and PlanetScale has a serverless driver that talks to the database over HTTP, which also works where TCP is not available.

Server Actions also have a request body limit of 1 MB by default. That is plenty for forms; for file uploads, raise serverActions.bodySizeLimit in next.config.ts or upload to object storage and store only the URL in MySQL.

Raw mysql2, Drizzle or Prisma?

Everything above uses raw mysql2, which keeps the moving parts visible. For a real project, this is the recommendation:

  • A few tables and a dozen queries: raw mysql2. You write SQL and the row types by hand, and there is nothing else to learn.
  • Most new Next.js and MySQL apps: Drizzle on top of the same pool. Queries look like SQL, results are typed from your schema, drizzle-kit generates migrations, and it adds little to the server bundle. It takes the pool you already have:
// lib/orm.ts
import "server-only";
import { drizzle } from "drizzle-orm/mysql2";
import { pool } from "./db";

export const db = drizzle({ client: pool });
  • Prisma when the team already uses it or wants a schema-first workflow with a generated client and Prisma Studio. It is a larger dependency and adds a code generation step to the build, which is a fair trade when the team knows it well.

Whatever you choose, the rules above stay the same: one pool, queries in server-only modules, checks in every action, and short transactions.

Errors you will probably meet

ErrorCauseFix
Too many connections (ER_CON_COUNT_ERROR)A new pool on every hot reload, or too many serverless instances times connectionLimitCache the pool on globalThis, lower connectionLimit, set idleTimeout, attach the pool on Vercel
Module not found: Can't resolve 'net' (or 'tls')mysql2 was pulled into a Client Component or an Edge routeImport the database only from server-only modules; keep those routes on the Node.js runtime
Incorrect arguments to mysqld_stmt_executeA number passed to LIMIT ? or OFFSET ? with executeUse query for that statement, or pass the values as strings
The page never shows new rows in productionWithout Cache Components, the page was prerendered at build timeawait connection() in the page, or tag the cached query and expire it from the action
The build fails with ECONNREFUSED or ETIMEDOUTA cached query runs during next build and the build machine cannot reach MySQLGive the build read access, or stop caching that query and stream it with Suspense
ER_LOCK_DEADLOCKTwo transactions waiting on each other's locksRetry the transaction once; keep transactions short and in a consistent order

Questions that come up

Can I use MySQL with Next.js?

Yes. Next.js runs server code in Server Components, Server Actions and route handlers, and that code can use any Node.js database driver. For MySQL that is usually mysql2, alone or underneath an ORM such as Drizzle or Prisma.

Do I need an API route to use MySQL in Next.js?

Not for your own pages. Read in Server Components and write in Server Actions. Write a route handler when something outside the app calls you: a mobile app, a webhook, a partner integration. The Next.js API routes and route handlers guide covers those.

Is it safe to put SQL in a Server Component?

Yes. Server Components are not sent to the browser, so the SQL and the credentials stay on the server. The risks are the usual ones: string-built SQL (use placeholders), missing authorization checks (do them in every action and in queries that return private data), and accidentally importing the database module into a Client Component (server-only stops that at build time).

Can I use MySQL on the Edge runtime or in middleware?

Not with mysql2, which needs TCP sockets. Keep database code on the Node.js runtime, which is the default. If you need data at the edge, use an HTTP-based driver from your database provider, or move the check into the page.

How many connections should my pool have?

Start with 5 per process on serverless and 10 to 20 on a single long-running server. Then check the number against MySQL's max_connections multiplied out by how many processes or instances you run at peak.

Sources and docs