Created
February 4, 2024 06:25
-
-
Save aryanprince/e5c75f1d150db83a32ebb73e7350d4c0 to your computer and use it in GitHub Desktop.
Singleton Drizzle client during dev, to prevent errors from Next.js HMR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { drizzle } from "drizzle-orm/postgres-js"; | |
import postgres from "postgres"; | |
import { env } from "~/env.js"; | |
import * as schema from "./schema"; | |
import { type PostgresJsDatabase } from "drizzle-orm/postgres-js"; | |
// Fix for "sorry, too many clients already" | |
declare global { | |
// eslint-disable-next-line no-var -- only var works here | |
var db: PostgresJsDatabase<typeof schema> | undefined; | |
} | |
let db: PostgresJsDatabase<typeof schema>; | |
if (env.NODE_ENV === "production") { | |
db = drizzle(postgres(env.DATABASE_URL), { schema }); | |
} else { | |
if (!global.db) global.db = drizzle(postgres(env.DATABASE_URL), { schema }); | |
db = global.db; | |
} | |
export { db }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment