Hornster
Hornster
PPrisma
Created by Hornster on 11/19/2024 in #help-and-questions
nextjs + prisma: rawQuery breaking if using globalThis
I think I can mark this as solved for now. as mentioned above, storing references to the helper functions on globalThis seems to work - but there is no mention of that in the documentation. so my suggestion: the troubleshooting page for nextjs should also mention this.
6 replies
PPrisma
Created by Hornster on 11/19/2024 in #help-and-questions
nextjs + prisma: rawQuery breaking if using globalThis
its a bit different, as I need multiple client instances due to a multi tenant setup.
import { PrismaClient as PrismaClientTenant } from './client'

function tenantSchemaUrl(tenantId: number) {
const dbUrlBase = process.env.DB_URL_BASE
return `${dbUrlBase}?schema=tenant_${tenantId}`
}

declare const globalThis: {
[K in string]: PrismaClientTenant
} & typeof global;

function generateClient(tenantId: number) {
const databaseUrl = tenantSchemaUrl(tenantId)
const client = new PrismaClientTenant({
datasources: {
db: {
url: databaseUrl
}
}
})
return client
}

export function prismaClientTenant(tenantId: number) {
const key = `prisma_tenant_${tenantId}`
if (!globalThis[key]) {
const client = generateClient(tenantId)
globalThis[key] = client
}

return globalThis[key]
}
import { PrismaClient as PrismaClientTenant } from './client'

function tenantSchemaUrl(tenantId: number) {
const dbUrlBase = process.env.DB_URL_BASE
return `${dbUrlBase}?schema=tenant_${tenantId}`
}

declare const globalThis: {
[K in string]: PrismaClientTenant
} & typeof global;

function generateClient(tenantId: number) {
const databaseUrl = tenantSchemaUrl(tenantId)
const client = new PrismaClientTenant({
datasources: {
db: {
url: databaseUrl
}
}
})
return client
}

export function prismaClientTenant(tenantId: number) {
const key = `prisma_tenant_${tenantId}`
if (!globalThis[key]) {
const client = generateClient(tenantId)
globalThis[key] = client
}

return globalThis[key]
}
As every tenant needs a different default schema in the client's database url, I ended up going with this. It seems to work - the client is created when I first call prismaClientTenant(), and then on subsequent calls it always returns the same instance stored on globalThis. as for the helper functions Prisma.raw etc - storing a reference to them on globalThis also seems to fix my issue 🤔
6 replies