Singleton instance of a Temporal Client connection in Nextjs

AFAIK, the Temporal Client instance should be a singleton that is reused throughout the lifetime of an application. However the Nextjs example here :

show a client being instantiated on every call. Is this example correct, or outdated? Or does the Temporal Client library somehow handle this internally?

Due to the way Nextjs handles pages (which is basically implemented as a lambda), I searched around on the most common singleton use-case which is a database connection, and came across this from the Prisma ORM :

They suggest declaring a global object and reusing the connection this way. I’m thinking about implementing the client the same way, but I’m wondering if I should do so considering Temporal’s official documentation and sample code does not do this.

I ended up just implementing the singleton client the same way the Prisma docs that I linked above does it. Tested it out locally on my Nextjs project and it seems to work well. Here is my code :

import { Connection, WorkflowClient } from '@temporalio/client'

const globalTemporal = global as unknown as { client: WorkflowClient }

export const getTemporalClient = async () => {
  if (globalTemporal.client) {
    return globalTemporal.client;
  const connection = await Connection.connect({
    address: 'localhost:7233'

  globalTemporal.client = new WorkflowClient({
    namespace: 'default'
  console.log("NEW TEMPORAL CLIENT CREATED"); // This only prints on the first api call as it should

  return globalTemporal.client;

Although I don’t know how this implementation may be affected if actually deploying the routes as serverless functions; I assume that if the instance does not exist in the application context my implementation will return a new client instance anyways, so it should work in any case.

If you mean the

const client = new WorkflowClient();

call in the first link you mentioned, yes I think there is no need to create this on every request and reusing the client is recommended. Think adding a comment on this line of code to mention this in docs would be good to do, will let the docs team know.