Next.js Discord

Discord Forum

Drizzle + RSC = infinite loading

Unanswered
Yellow-billed Cuckoo posted this in #help-forum
Open in Discord
Yellow-billed CuckooOP
Hello, I am using next 14 + React 18 + Drizzle + Postgres. When I run a drizzle query in a RSC, it causes the app to be stuck in a loading state, but the query completes and logs correctly on the server. It is almost like the RSC is never hitting a "loaded" state? Maybe it is waiting for the DB connection to close? I have no clue what is going on...

I am doing the thing where you create a global drizzle client, so it doesn't keep creating connections. Could this be the issue?
// db.ts
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import { parse, string } from 'valibot'
import * as schema from './schema'

export const db = getGlobal('db', () => {
  const url = parse(string(), process.env.DATABASE_URL)
  const connection = postgres(url, { ssl: 'require' })
  return drizzle(connection, { schema })
})

export function getGlobal<T>(key: string, callback: () => T): T {
  // eslint-disable-next-line no-undef
  const cache = globalThis as unknown as Record<string, T>
  if (process.env.NODE_ENV === 'production') return callback()
  return (cache[key] = cache[key] ?? callback())
}

// users.ts
'use server'

import { db } from './db'

export async function getUsers() {
   return await db.query.users.findMany()
}

// page.tsx
'use server'

import { getUsers } from './users'

export default async function Page() {
  const users = await getUsers()
  console.log(users) // this logs correctly
  // but this never returns
  return (
    <div>
      <div>Hello, world!</div>
    </div>
  )
}


Would really appreciate the help!

Thanks

Wilson

6 Replies

Im not sure what you are trying to do here but why is your db connection file so complicated?

Just export a drizzle() object and if you are using a service vercel postgres or like turso then you just create their client and pass it as the first argument to drizzle()
Yellow-billed CuckooOP
@Clown It's a pretty common pattern for local dev (I just wrote it slightly different) because of the way hot-reloading works, it can end up creating multiple connections and you will end up getting a "maximum connections reached" error from your database.
I figured it out! For anyone at Next who sees this... the problem was I had a root layout, but it only had an <html> tag and some context providers. Then, I had two route groups with their own layouts ((auth) and (main)) that had <body> as the root element because they want to handle styling on the body differently. Something about this was causing this error. I moved the root layout up, which causes some code duplication, but it works now
Didn't know I couldn't do this