Next.js Discord

Discord Forum

postgres.js and nextjs (14.0.2)

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
Hi. Im using postgres.js and suddenly I started getting this error every now and then while developing with npm run dev (still don't know if this will happend when the project is built). The error is:
Error: sorry, too many clients already
⨯ node_modules/postgres/src/connection.js (790:25) @ postgres
 ⨯ PostgresError: sorry, too many clients already


Here is what my code looks like:
// db.ts file
import {getEnvVar} from '@/lib/utils'
import postgres from 'postgres'
import {z} from 'zod'

const sql = postgres(getEnvVar('DATABASE_URL', z.string()), {max: 20})

export default sql

// user.ts file
export async function getUserById(id: number): Promise<DbUser> {
  const usersResp = await sql<Array<DbUser>>`
  select id, name from users
    where id = ${id}
  `
  const users = z.array(dbUser).parse(usersResp)
  if (users.length === 0) {
    throw new Error('user_not_found')
  }
  return users[0]
}

0 Replies