Hornster
Hornster
PPrisma
Created by Hornster on 11/19/2024 in #help-and-questions
nextjs + prisma: rawQuery breaking if using globalThis
Hi! I'm currently working on a nextjs (14.x) project, where I also want to use prisma (5.22). I have encountered an issue with nextjs always generating new clients in dev mode, so I followed the documentation and only generate the client, if it does not yet exist on globalThis. This seems to work when I use the client directly, but rawQueries only work on the first rendered route. As soon as a route has to be re-rendered (which happens very often in dev mode), the parameters no longer get properly resolved. Here is a simple example, queried with a freshly created client:
const fields = Prisma.raw(['id','name'].join(','))
const items = await prismaClient.$queryRaw`SELECT ${fields} FROM project WHERE id = ${projectId}`
const fields = Prisma.raw(['id','name'].join(','))
const items = await prismaClient.$queryRaw`SELECT ${fields} FROM project WHERE id = ${projectId}`
Checking the query log, the following query is executed:
query: SELECT id,name FROM project WHERE id = $1
params: [2]
query: SELECT id,name FROM project WHERE id = $1
params: [2]
So it seems the fields are put directly into the statement, and a placeholder is used for projectId. Now if I use a client assigned to globalThis, then on the first request this will work as well - but as soon as a prisma route needs to be re-compiled, the executed query changes:
query: SELECT $1 FROM project WHERE id = $2
params: [{"values":[],"strings":["id,name"]},2]
query: SELECT $1 FROM project WHERE id = $2
params: [{"values":[],"strings":["id,name"]},2]
This query will no longer work. Seems like as soon as nextjs compiles a new route, then certain parts of the Prisma namespace also get instantiated again, which in turn makes them no longer work with an older instance of the client? Not exactly sure what I can do to remedy this, other than just letting nextjs create new clients whenever it feels like it. Help would be greatly appreciated!
6 replies