NeonN
Neon11mo ago
6 replies
worthy-azure

Uncaught Exception: Error: Connection terminated unexpectedly

I have a Next.js app deployed on Vercel, using @neondatabase/serverless as a PostgreSQL client and @prisma/adapter-neon to integrate with Prisma. Occasionally, I get a Connection terminated unexpectedly error, which causes an unhandled exception and crashes the Node.js process with exit code 129 (SIGHUP). Here’s my setup:

import { Pool, neonConfig } from "@neondatabase/serverless";
import { PrismaNeon } from "@prisma/adapter-neon";
import { PrismaClient } from "@prisma/client";

const connectionString = process.env.DATABASE_URL || "";

// Local/test environment configuration
const isDevelopment = process.env.NODE_ENV === "development";
const isTest = process.env.NODE_ENV === "test";

if (isDevelopment || isTest) {
  const LOCAL_HOST = "db.localtest.me";

  const getLocalPort = () => (isTest ? 4445 : 4444);

  // Override fetchEndpoint
  neonConfig.fetchEndpoint = (host) => {
    if (host === LOCAL_HOST) {
      return `http://${host}:${getLocalPort()}/sql`;
    }
    return `https://${host}:${443}/sql`;
  };

  // Secure WebSocket condition
  const connectionStringUrl = new URL(connectionString);
  neonConfig.useSecureWebSocket = connectionStringUrl.hostname !== LOCAL_HOST;

  // wsProxy setting
  neonConfig.wsProxy = (host) => {
    if (host === LOCAL_HOST) {
      return `${host}:${getLocalPort()}/v2`;
    }
    return `${host}/v2`;
  };
}

const pool = new Pool({ connectionString });
const adapter = new PrismaNeon(pool);
const prisma = new PrismaClient({ adapter });

export { prisma };

Despite using the @neondatabase/serverless pool, which should be suited for serverless environments, I still see intermittent disconnections reported by Vercel logs. Does anyone know what might cause this in a serverless environment, and how to prevent these unexpected terminations?
Was this page helpful?