
Neon WebSocket Connection Failed? 3 Fixes, Prisma + Drizzle
Skilldham
Engineering deep-dives for developers who want real understanding.
Last updated: November 2026
TL;DR
A Neon WebSocket connection failed error means the driver could not open its socket. The text after Details: tells you why. Read that part first, then pick the fix.
Details: fetch failed - your Node.js runtime has no WebSocket. Move to Node 22+ or set ws.
Details: ws does not work in the browser - you shipped ws to an Edge runtime. Remove it there.
Details: undefined - an old driver is hiding the error. Upgrade @neondatabase/serverless to 1.x.
You deploy. The first request hits the database. Then the logs show this:
bash
# Verbatim error from @neondatabase/serverless 0.10.x
Error: All attempts to open a WebSocket to connect to the database failed.
Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined.
Details: fetch failedIt worked on your laptop. You open the Neon forum and find a thread with 19 replies.
Everyone says the same thing. Add the ws polyfill. You add it, and now your middleware breaks with a new message.
Here’s the truth. Neon WebSocket connection failed is one headline with at least three causes. The fix depends on one line most people skip.
This post covers Prisma 7 with @prisma/adapter-neon and Drizzle ORM, on driver 0.10.x and 1.x.
What “All Attempts to Open a WebSocket” Really Means
The Neon serverless driver does not use raw TCP. Its Pool and Client tunnel Postgres through a WebSocket. Prisma’s PrismaNeon adapter and Drizzle’s neon-serverless driver both sit on that Pool.
The two attempts behind “all attempts”
“All attempts” sounds like retries. It is not. The driver tries exactly two things, in order.
First, it builds a WebSocket. It uses neonConfig.webSocketConstructor if you set one. If not, it uses the global WebSocket.
If that constructor throws, the driver falls back to fetch. It sends an Upgrade: websocket header and hopes for a socket back. Only Cloudflare Workers can return a socket from fetch.
javascript
// Simplified from @neondatabase/serverless 1.2.1 - how the driver opens its socket
try {
const Ctor = neonConfig.webSocketConstructor ?? globalThis.WebSocket;
socket = new Ctor(`wss://${host}/v2`); // attempt 1
} catch (constructorError) {
try {
// attempt 2: only Cloudflare Workers return a socket from fetch
const res = await fetch(`https://${host}/v2`, { headers: { Upgrade: 'websocket' } });
if (!res.webSocket) throw constructorError;
} catch (err) {
throw new Error(`All attempts to open a WebSocket ... Details: ${err}`);
}
}Why the Details suffix is the real error
The text after Details: is the last thing that failed. Sometimes that is the fetch error. Sometimes it is the constructor error, thrown again.
Driver 0.10.x prints only the message, like fetch failed. Driver 1.x prints the full error, like TypeError: fetch failed. So one headline hides three different bugs, and the suffix is your diagnosis.

Neon WebSocket Connection Failed - Map the Details Line
I reproduced every variant below on Node 22.23 with driver 1.2.1 and 0.10.4. Each one points to a different runtime problem.
The Details lookup table
Details valueWhere you see itReal causeFixfetch failed or TypeError: fetch failedNode.js 18, 20 or 21No global WebSocket, and no ws setNode 22+, or set wsws does not work in the browser...Vercel Edge, middleware.ts, Cloudflarews bundled into an Edge runtimeRemove ws there, or use the HTTP driverundefinedDriver 0.x onlyThe thrown value had no messageUpgrade to driver 1.x, then read againNo “All attempts” headline. You see Received network error or non-101 status code.Node 22+Socket was built, but the handshake failedCheck the host, the local proxy, the firewall
The last row matters. On Node 22+, a real network problem never produces the “All attempts” headline at all.
Log the full error, not a summary
Many apps swallow the driver error. Then you debug a generic “Database error” for an hour.
typescript
// Wrong: the Details line never reaches your logs
try {
await prisma.user.findMany();
} catch {
console.error('Database error');
}This hides the one line you need. You can’t map a cause you never see.
typescript
// Correct: Prisma 7 - surface raw driver errors with the adapter hooks
import { PrismaNeon } from '@prisma/adapter-neon';
import { PrismaClient } from '@/generated/prisma/client';
const adapter = new PrismaNeon(
{ connectionString: process.env.DATABASE_URL! },
{
onPoolError: (err) => console.error('[neon pool]', err.message),
onConnectionError: (err) => console.error('[neon conn]', err.message),
},
);
export const prisma = new PrismaClient({ adapter });onPoolError and onConnectionError are real options on PrismaNeon in Prisma 7. They print the driver message before Prisma wraps it.
Details: fetch failed - Your Node Runtime Has No WebSocket
This is the most common variant. Node 22 ships a global WebSocket. Node 20 does not, unless you pass a flag.
Prisma 7 still supports Node 20.19+. So “Prisma 7 on Node 20” is legal, and it breaks this exact way.
Why “fetch failed” is not a network error
This is the part most threads get wrong. “fetch failed” sends you to check DNS, firewalls and Neon status. That is the wrong direction.
In Node.js, the fallback fetch can never succeed. Node’s fetch comes from undici. Undici rejects the Upgrade header before any network call.
bash
# Reproduce it: Node's fetch refuses the Upgrade header with no network call
node -e 'fetch("https://example.com/v2",{headers:{Upgrade:"websocket"}}).catch(e=>console.log(String(e),"|",String(e.cause)))'
# Output: TypeError: fetch failed | InvalidArgumentError: invalid upgrade headerSo in Node, fetch failed really means attempt 1 threw. There was no WebSocket to build.
Fix 1 - run Node 22+ and delete the polyfill
typescript
// Wrong: Node 20 runtime, no WebSocket, no ws - fails on the first query
import { PrismaNeon } from '@prisma/adapter-neon';
import { PrismaClient } from '@/generated/prisma/client';
const adapter = new PrismaNeon({ connectionString: process.env.DATABASE_URL! });
export const prisma = new PrismaClient({ adapter });The code is fine. The runtime is the bug. Check what your server really runs:
bash
# Check the Node version your code actually runs on
node -v
# On Vercel, also check the Node.js Version in your project settingsThen pin Node 22+ in package.json, so every platform agrees:
json
{
"engines": {
"node": ">=22"
}
}Now the same code works with no ws at all. Add a startup guard, so a wrong runtime fails loudly.
typescript
// Correct: lib/prisma.ts - Prisma 7 + Neon on Node 22+, native WebSocket, no ws
import { PrismaNeon } from '@prisma/adapter-neon';
import { PrismaClient } from '@/generated/prisma/client';
if (typeof globalThis.WebSocket === 'undefined') {
throw new Error(
`No global WebSocket on Node ${process.version}. Use Node 22+ or set neonConfig.webSocketConstructor.`,
);
}
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
const adapter = new PrismaNeon({ connectionString: process.env.DATABASE_URL! });
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;The import path must match your Prisma 7 generator output:
prisma
// Correct: Prisma 7 schema - no url in datasource, output matches the import above
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}Drizzle needs even less code on Node 22+. Still picking an ORM? Read Prisma vs Drizzle for Next.js first.
typescript
// Correct: db/index.ts - Drizzle + Neon WebSocket driver on Node 22+, no ws
import { drizzle } from 'drizzle-orm/neon-serverless';
import * as schema from './schema';
export const db = drizzle({ connection: process.env.DATABASE_URL!, schema });Here’s why this works. The driver finds globalThis.WebSocket and attempt 1 succeeds. Nothing extra gets bundled, so the old bufferutil warnings from ws also go away.
Munshi runs Prisma 7 with this exact adapter setup in production. Dropping ws there removed a dependency and a class of bundling bugs.
Fix 2 - stuck on Node 20? Set ws once
Node 20 reached end of life in April 2026. If you can’t move yet, register ws before the first query.
bash
# Install ws and its types for Node 20 only
npm install ws
npm install -D @types/wstypescript
// Correct: Node 20 only - register ws before any Pool is created
import { neonConfig } from '@neondatabase/serverless';
import ws from 'ws';
neonConfig.webSocketConstructor = ws;For Drizzle, pass it straight to the driver:
typescript
// Correct: Drizzle on Node 20 - hand ws to the neon-serverless driver
import { drizzle } from 'drizzle-orm/neon-serverless';
import ws from 'ws';
import * as schema from './schema';
export const db = drizzle({ connection: process.env.DATABASE_URL!, ws, schema });One trap remains. @prisma/adapter-neon has its own dependency on the driver. If npm installs two copies, your neonConfig lands on the wrong one.
bash
# Check for duplicate driver copies - you want exactly one version
npm ls @neondatabase/serverlessDetails: ws does not work in the browser - Edge Runtime
This is the polyfill backfiring. The ws package has a browser build. Bundlers pick it for Edge and client bundles.
That browser build throws the moment you construct it. On Edge, the fetch fallback returns a response with no socket. So the driver rethrows the constructor error, and you see this:
bash
# Details line when ws reaches an Edge bundle (headline shortened)
All attempts to open a WebSocket to connect to the database failed. Details: ws does not work in the browser.
Browser clients must use the native WebSocket objectThe shared db file that breaks Edge
typescript
// Wrong: lib/db.ts forces ws, and an Edge file imports it
import { neonConfig } from '@neondatabase/serverless';
import { PrismaNeon } from '@prisma/adapter-neon';
import { PrismaClient } from '@/generated/prisma/client';
import ws from 'ws';
neonConfig.webSocketConstructor = ws; // fine on Node, fatal on Edge
const adapter = new PrismaNeon({ connectionString: process.env.DATABASE_URL! });
export const prisma = new PrismaClient({ adapter });
// middleware.ts or an Edge route then does: import { prisma } from '@/lib/db';Edge runtimes already have a native WebSocket. Forcing ws replaces a working constructor with one that always throws. This is why “just add ws” is wrong advice for Edge.
Not sure where your code runs? Log it once:
typescript
// Correct: print the runtime your code really runs in
const runtime = typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime === 'string'
? 'edge'
: `node ${process.version}`;
console.log('[runtime]', runtime);Fix - use the HTTP driver on Edge
For Edge, skip WebSockets entirely. Neon’s HTTP driver sends each query as one fetch call.
typescript
// Correct: lib/prisma-edge.ts - Prisma 7 over HTTP, safe in Edge runtimes
import { PrismaNeonHttp } from '@prisma/adapter-neon';
import { PrismaClient } from '@/generated/prisma/client';
const adapter = new PrismaNeonHttp(process.env.DATABASE_URL!, {});
export const prismaEdge = new PrismaClient({ adapter });typescript
// Correct: db/edge.ts - Drizzle over HTTP for Edge and Cloudflare Workers
import { drizzle } from 'drizzle-orm/neon-http';
import * as schema from './schema';
export const db = drizzle(process.env.DATABASE_URL!, { schema });Know the trade-off before you switch. PrismaNeonHttp rejects transactions with “Transactions are not supported in HTTP mode”. Drizzle’s neon-http has no interactive transactions either, but it does offer db.batch().
Keep two files: prisma.ts for Node and prisma-edge.ts for Edge. Never let an Edge file import the Node one. And never import ws from a client component.
Next.js 16 proxy.ts removes the problem
Most Edge database calls live in middleware.ts for auth checks. Next.js 16 renamed middleware to proxy.ts.
Proxy runs on the Node.js runtime, and you can’t switch it to Edge. So your Node prisma.ts works there as-is. The old middleware.ts still runs on Edge, but it is deprecated.
Details: undefined - The Old Driver Hiding the Error
This variant is the most annoying. The headline appears, but the suffix says nothing.
Why you see the word undefined
Driver 0.10.x builds the line with err.message. If the thrown value has no message property, you get undefined. The failure is real, but the driver drops its description.
javascript
// Wrong: how driver 0.10.x builds the Details line
`... Details: ${err.message}` // a value with no message prints "undefined"Driver 1.x changed this. It prints the whole error with ${err}, including its type.
Fix - upgrade, then read the line again
bash
# Correct: upgrade the driver, then confirm only one copy exists
npm install @neondatabase/serverless@^1.2.1
npm ls @neondatabase/serverlessDriver 1.x needs Node 19 or newer. After the upgrade, rerun the failing request. You’ll get a real Details: value, and the table above maps it.
Driver 1.x also catches a missing env var early. If DATABASE_URL is empty, it says so directly:
bash
# Verbatim driver 1.2.1 message when DATABASE_URL is missing
Error: No database host or connection string was set, and key parameters have default values
(host: localhost, user: undefined, db: undefined, password: null). Is an environment variable missing?Local Development Without Breaking Production
Local setups cause the rest of the forum threads. Someone points the driver at a local proxy, then ships that config.
The easy path - a Neon dev branch
The simplest local setup has no local database at all. Create a Neon branch and put its URL in .env.local.
Your laptop then runs the same code path as production. No proxy, no special flags, no surprises on deploy.
Local Postgres through a WebSocket proxy
If you need fully offline work, run Postgres with a Neon-compatible proxy.
yaml
# Correct: docker-compose.yml - local Postgres plus a Neon-style WebSocket proxy
services:
postgres:
image: postgres:17
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: main
ports:
- '5432:5432'
neon-proxy:
image: ghcr.io/timowilhelm/local-neon-http-proxy:main
environment:
- PG_CONNECTION_STRING=postgres://postgres:postgres@postgres:5432/main
ports:
- '4444:80'
depends_on:
- postgrestypescript
// Wrong: rewires the driver for every environment, including production
import { neonConfig } from '@neondatabase/serverless';
neonConfig.wsProxy = (host) => `${host}:4444/v2`;
neonConfig.useSecureWebSocket = false;This ships to production too. Your deployed app then tries a plain ws:// socket on port 4444.
typescript
// Correct: lib/neon-local.ts - only rewire the driver for the local host
import { neonConfig } from '@neondatabase/serverless';
const LOCAL_HOST = 'db.localtest.me';
export function configureNeonForLocal(connectionString: string) {
if (new URL(connectionString).hostname !== LOCAL_HOST) return;
neonConfig.wsProxy = (host) => `${host}:4444/v2`;
neonConfig.useSecureWebSocket = false;
neonConfig.pipelineTLS = false;
neonConfig.pipelineConnect = false;
neonConfig.fetchEndpoint = (host) => `http://${host}:4444/sql`;
}bash
# .env.local - db.localtest.me resolves to 127.0.0.1
DATABASE_URL="postgres://postgres:postgres@db.localtest.me:5432/main"Call configureNeonForLocal(process.env.DATABASE_URL!) before you create the adapter. The hostname check means a real Neon URL never touches these settings.
Received network error or non-101 status code
This message means the socket was built, but the handshake failed. On Node 22+, it is what a dead local proxy looks like.
Run docker compose ps and confirm the proxy is up on port 4444. Then check the host in your URL for typos.
After the Fix - The Pool Errors That Come Next
Once the socket opens, you are on a real connection pool. That brings a second set of problems.
Pool timeouts under serverless load
In Prisma 7 with the Neon adapter, the pool belongs to the Neon driver. The connection_limit and pool_timeout URL params do nothing.
typescript
// Wrong: Prisma 7 ignores pool params in the URL with the Neon adapter
const adapter = new PrismaNeon({
connectionString: `${process.env.DATABASE_URL}&connection_limit=5&pool_timeout=20`,
});typescript
// Correct: Prisma 7 - pool options go on the Neon adapter config
import { PrismaNeon } from '@prisma/adapter-neon';
const adapter = new PrismaNeon({
connectionString: process.env.DATABASE_URL!,
max: 10,
connectionTimeoutMillis: 15_000,
idleTimeoutMillis: 10_000,
});If requests still queue, the Prisma pool timeout fix for serverless covers sizing for spiky traffic.
Connections that never close
Long-lived Node servers hit the opposite problem. Idle sockets stay open and the process never exits cleanly.
idleTimeoutMillis controls when idle connections close. The full debugging story is in why idleTimeoutMillis does not close the Prisma pool.
Still setting up from scratch? Start with the Prisma 7 NeonDB driver adapter setup for Next.js. It covers prisma.config.ts and the generator output path.
Key Takeaways
A Neon WebSocket connection failed error has several causes. The Details: suffix names the one you have.
In Node.js, Details: fetch failed is not a network error. Undici blocks the Upgrade header, so it means no WebSocket existed.
On Node 22+, delete the ws polyfill. The native WebSocket works with PrismaNeon and Drizzle’s neon-serverless.
Never ship ws to Edge. Use PrismaNeonHttp or drizzle-orm/neon-http, and accept no interactive transactions.
Details: undefined comes from driver 0.x. Upgrade to 1.x and read the real error.
Gate local proxy settings on the hostname, not on a global flag. Or skip the proxy and use a Neon dev branch.
Run npm ls @neondatabase/serverless when ws is set but ignored. Two copies mean two configs.
FAQ
Does Prisma 7 still need the ws package for Neon?
Only on Node 20 or older. On Node 22+, PrismaNeon uses the global WebSocket with no extra setup. Remove ws and pin "node": ">=22" in package.json.
Why do I get “Details: fetch failed” when my network is fine?
Because it is not a network error in Node.js. The driver’s fallback fetch sends an Upgrade header, and undici rejects it. The real cause is a missing WebSocket constructor.
I set neonConfig.webSocketConstructor = ws and still get the error. Why?
You likely have two copies of @neondatabase/serverless. Your setting lands on one, and the adapter uses the other. Run npm ls @neondatabase/serverless and dedupe to one version.
Can I use the ws polyfill in Next.js middleware or the Edge runtime?
No. Bundlers load the browser build of ws, which throws on construct. Use the HTTP driver on Edge, or move the logic to proxy.ts in Next.js 16.
Does the Neon WebSocket error happen with Drizzle too?
Yes. drizzle-orm/neon-serverless uses the same driver Pool, so the same three causes apply. On Node 20, pass ws to drizzle(), and on Edge, use drizzle-orm/neon-http.
Should I use the Neon HTTP driver or the WebSocket driver?
It depends on transactions. Use the WebSocket driver on Node.js when you need interactive transactions or sessions. Use the HTTP driver on Edge or for simple one-shot queries.
Why does it work locally but fail on Vercel?
Your laptop and Vercel often run different Node versions. Local Node 22 has a global WebSocket, while an older project setting may not. Check the Node.js version in project settings and pin it with engines.
What does “No database host or connection string was set” mean?
DATABASE_URL is empty at runtime, so the driver defaulted to localhost. Driver 1.x reports this directly. Check that the variable exists in the environment where the code runs.
Wrapping Up
A Neon WebSocket connection failed message looks the same every time, but the cause is not. Read the Details: line, map it to your runtime, and apply that one fix.
This matters because the popular fix only solves one case. On Node 22+, ws is dead weight, and on Edge it is the bug itself.
Socket open but the pool timing out? The Prisma pool timeout guide is your next stop.
Want fixes like this for Prisma, Neon and Next.js in your inbox? Subscribe to the SkillDham newsletter.