How to prevent Next.js from instantiating a singleton class/object multiple times?

In development, Next clears Node.js cache on run, so every time there is a “compiling…” in the terminal, it starts as a new app, losing any previous variable.

This is why, in this article, written by Next.js team, down to the section where they instantiate a PrismaClient, to have it created only once, they use the global object, in your case, like so:

let analytics;

if (process.env.NODE_ENV === "production") {
  analytics = new Analytics();
} else {
  if (!global.analytics) {
    global.analytics = new Analytics();
  }
  analytics = global.analytics;
}

export default analytics;

Leave a Comment