Prisma and Supabase: "prepared statement s0 already exists" and "max clients reached" on Vercel
By AI App Medic · Updated · Supabase · Prisma · Vercel · Database
The app works on your machine. Deployed to Vercel, pages that read from the database start failing, often after a few refreshes or under a little traffic, and the function logs show one of these:
Invalid `prisma.post.findMany()` invocation:
Error occurred during query execution:
ConnectorError(... code: "42P05", message: "prepared statement \"s0\" already exists" ...)
Error querying the database: FATAL: MaxClientsInSessionMode: max clients reached
- in Session mode max clients are limited to pool_size
Can't reach database server at `db.abcdefghijkl.supabase.co:5432`
In the browser you only see "An error occurred in the Server Components render" or a 500. All three come from the same decision: which of Supabase's three connection strings the app uses, and whether Prisma knows a pooler sits in between. Cursor and v0 usually paste whatever string was on screen into .env, and the defaults that work locally are the wrong ones for serverless.
Step 1: know the three connection strings
In the Supabase dashboard, open your project and click Connect. You will see:
- Direct connection:
db.PROJECT-REF.supabase.co:5432. One real Postgres connection per client. The host resolves to IPv6 unless you buy the IPv4 add-on, so many serverless and CI environments cannot reach it. That is the "Can't reach database server" error. - Session pooler:
aws-0-REGION.pooler.supabase.com:5432(the prefix may beaws-1), userpostgres.PROJECT-REF. Works over IPv4. Each client keeps one database connection for as long as it stays connected, so the pool runs out when many serverless instances connect at once. That isMaxClientsInSessionMode. - Transaction pooler: the same host on port
6543. A database connection is lent out for one transaction and then returned, so hundreds of short-lived functions can share a small pool. This is the one Supabase recommends for serverless. It does not support prepared statements, which is whereprepared statement "s0" already existscomes from when Prisma is not told about it.
Check which one the deployed app uses. In Vercel, open Project Settings, Environment Variables, and look at DATABASE_URL for Production. The host and port tell you which case you are in. Remember that your local .env.local can differ from what Vercel has.
Step 2: why Prisma breaks on port 6543
Prisma prepares its queries as named statements, s0, s1 and so on, and remembers which ones it already created on its connection. Behind a transaction pooler, Prisma's connection is not tied to one database connection. Its next transaction can run on a database connection where another instance already created s0, and Postgres refuses to create it twice (error 42P05). The reverse case, a statement created on one connection and executed on another, gives prepared statement "s0" does not exist (26000). The pgbouncer=true parameter switches Prisma to a mode that does not depend on prepared statements surviving between transactions. Supabase's own Prisma guide says to append it to the transaction pooler string.
Step 3: set the runtime URL
For the app on Vercel, use the transaction pooler with pgbouncer=true. On Prisma 6 and earlier, also cap each function instance at one connection, as Prisma recommends for serverless:
# Vercel, Production and Preview
DATABASE_URL="postgresql://postgres.PROJECT-REF:PASSWORD@aws-0-REGION.pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1"
If the password contains characters such as @, #, / or %, URL-encode them, or the string is parsed wrongly and you get authentication or host errors that look unrelated. Copy the string from the Connect dialog instead of typing it, because the region and the aws-0 or aws-1 prefix must match your project.
Old projects and old tutorials use db.PROJECT-REF.supabase.co:6543 for pooling. That was Supabase's earlier PgBouncer setup and is no longer the pooler endpoint. Use the pooler.supabase.com host from the dashboard.
Step 4: give migrations a separate URL
prisma migrate needs one stable session and fails through the transaction pooler, often with the same s0 error. Add a second variable on port 5432, the session pooler or the direct connection if your network has IPv6:
DIRECT_URL="postgresql://postgres.PROJECT-REF:PASSWORD@aws-0-REGION.pooler.supabase.com:5432/postgres"
On Prisma 5 and 6, point the schema at both:
// prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
On Prisma 7 the connection URL moved out of the schema. The CLI reads it from prisma.config.ts, and the app passes the pooled URL to a driver adapter:
// prisma.config.ts (used by prisma migrate, db push, db pull)
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
datasource: { url: env("DIRECT_URL") },
});
// lib/prisma.ts (used by the app)
import { PrismaClient } from "@/generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, max: 1 });
export const prisma = new PrismaClient({ adapter });
The import path for PrismaClient depends on the output set in your generator block. On Prisma 7 the connection_limit URL parameter no longer controls the pool; the max option of the adapter does. Run migrations from your machine or a CI step with DIRECT_URL set, not from inside a request handler.
Step 5: create PrismaClient once
AI-generated code often calls new PrismaClient() in several files, or inside a function that runs on every request. Each instance opens its own pool. In development, Next.js hot reload creates a new one on every save until you see "too many connections". Use one shared module:
// lib/prisma.ts (Prisma 6 and earlier)
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
Then search the project for new PrismaClient and replace every other occurrence with an import from this file.
Step 6: redeploy and check
Changing an environment variable in Vercel does not affect the running deployment. Redeploy, then load the pages that query the database several times quickly, or open them in a few tabs at once, and watch the function logs. If the s0 error is still there:
- Print the host, port and whether the URL contains
pgbouncer=true(never the password) from a temporary route, to confirm what the deployment really reads. A Preview environment, a.envcommitted to the repo, or a second variable such asPOSTGRES_PRISMA_URLfrom a Vercel integration can win over the one you edited. Environment variable precedence on Vercel is covered in Next.js environment variables undefined on Vercel. - Make sure nothing else, such as a seed script or a cron route, uses the pooled URL without the parameter.
- If the build fails because a page queries the database during prerendering, mark that page dynamic with
export const dynamic = "force-dynamic"or make sure the build can reach the pooler. Other build errors are covered in Cursor app Vercel build failed.
Once connections are fixed, slow queries may show up as a different error. If you start seeing canceling statement due to statement timeout, see that guide.
A note on security
The Prisma connection string carries the database password and usually connects as postgres, which bypasses row level security. It must only ever be used in server code. Never put it in a NEXT_PUBLIC_ variable, and do not import lib/prisma.ts from a client component. Supabase suggests creating a separate database user for Prisma, so you can rotate its password and track its queries without touching the postgres user. If the Supabase Data API is not used at all because Prisma does everything, consider turning the Data API off so the anon key cannot be used to read tables directly.
Prevention
Decide the connection setup on day one: transaction pooler with pgbouncer=true for the app, port 5432 for migrations, two variables, one shared client. Write it into the project README so the next AI prompt does not "simplify" it back to one URL. Before launch, hit the deployed app with a few dozen parallel requests, for example with npx autocannon -c 20 -d 10 https://your-app.vercel.app/ on a page that reads the database, and check the logs for connection errors. Keep an eye on the database connections chart in Supabase reports after each release.
FAQ
What causes prepared statement s0 already exists with Supabase?
Prisma uses named prepared statements, and Supabase's transaction pooler on port 6543 hands each transaction to whichever database connection is free. A statement prepared by one client is then found on a connection another client uses, and Postgres refuses to create s0 a second time. Adding pgbouncer=true tells Prisma not to rely on prepared statements.
Which Supabase port should Prisma use on Vercel?
Use the transaction pooler on port 6543 with pgbouncer=true for the running app, because serverless functions open many short connections. Use port 5432, through the session pooler or the direct connection, only for prisma migrate and other CLI commands.
What does MaxClientsInSessionMode: max clients reached mean?
The app is connected through the session pooler on port 5432, where each client holds a database connection for as long as it stays connected. Parallel Vercel functions use up the pool size quickly. Move the app to the transaction pooler on port 6543 instead of raising the pool size.
Why does prisma migrate fail with prepared statement already exists?
Migrate needs a single direct session and does not work through the transaction pooler. Give the CLI its own DIRECT_URL on port 5432, using directUrl in schema.prisma on Prisma 5 and 6 or the datasource url in prisma.config.ts on Prisma 7.
Why can't Vercel reach db.PROJECT.supabase.co?
Supabase's direct connection host resolves to an IPv6 address unless you have the IPv4 add-on, and many serverless and CI environments only have IPv4. Use the pooler host, pooler.supabase.com, which accepts IPv4 on both 5432 and 6543.
I added pgbouncer=true and still get the error. What now?
Check that the deployed DATABASE_URL really contains it: a .env.local or a Vercel environment for another branch often overrides the value you edited. Redeploy so no old instance keeps the previous URL, and make sure every PrismaClient in the code uses the same variable.
Related guides
- Supabase "canceling statement due to statement timeout": why queries die after 3 or 8 seconds
- Next.js environment variables undefined on Vercel: NEXT_PUBLIC_, redeploys and "supabaseUrl is required"
- Cursor app Vercel build failed: fix the error that npm run dev never showed
- Supabase PGRST116 "JSON object requested, multiple (or no) rows returned": what .single() is telling you
- Supabase upsert: "there is no unique or exclusion constraint matching the ON CONFLICT specification"