Next.js Discord

Discord Forum

Singleton client being instantiated multiple times

Unanswered
Havana posted this in #help-forum
Open in Discord
HavanaOP
I have this file in my next.js app where I want to instantiate my runtime (think of it like a "client"), I store it in a local variable and expect the createAppRuntime to only be called once.

Yet, I see it being called from time to time, with no pattern that I can figure out. This leads to me having errors like "Too many clients" with my database connection.

What am I missing? This should only be called once, right? In dev I see this function being executed 3 times on a page refresh!

const createAppRuntime = () => {
    // eslint-disable-next-line no-console
    console.log(">>>> Creating App Runtime...");

    const AppLive = pipe(
        IDGeneratorLive,
        Layer.provideMerge(SqlLive),
    );

    return ManagedRuntime.make(AppLive);
};


const globalForRuntime = global as unknown as { runtime: AppRuntime | undefined };

export const appRuntime =
    globalForRuntime.runtime || createAppRuntime();

if (process.env.NODE_ENV !== "production") globalForRuntime.runtime = appRuntime;

4 Replies

HavanaOP
It happens with both next 14.2.9 and 15.1.0
i still see this function called multiple times even if I wrap it with React.cache
it seems to be related with this: https://github.com/vercel/next.js/issues/49309

how do people work around this? 😓