Skip to content

Instantly share code, notes, and snippets.

@aryanprince
Created February 4, 2024 06:25
Show Gist options
  • Save aryanprince/e5c75f1d150db83a32ebb73e7350d4c0 to your computer and use it in GitHub Desktop.
Save aryanprince/e5c75f1d150db83a32ebb73e7350d4c0 to your computer and use it in GitHub Desktop.
Singleton Drizzle client during dev, to prevent errors from Next.js HMR
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