Home > other >  How to prevent Next.js from instantiating the same object multiple time, one per import?
How to prevent Next.js from instantiating the same object multiple time, one per import?

Time:01-29

I have an analytics utility like this:

class Analytics {
    data: Record<string, IData>;

    constructor() {
        this.data = {};
    }
    setPaths(identifier: string) {
        if (!this.data[identifier])
            this.data[identifier] = {
                generic: getGenericInit(),
                session: getSessionInit(),
                paths: {
                    geoCollectionPath: '',
                    sessionCollectionPath: '',
                    eventsCollectionPath: ''
                }
            };
        this.data[identifier].paths = {
            geoCollectionPath: getGeoPath(identifier),
            sessionCollectionPath: getSessionPath(identifier),
            eventsCollectionPath: getEventPath(identifier)
        };
    }
    getAll() {
        return this.data;
    }
}

const analytics = new Analytics();
export default analytics;

And I import it into 2 api folders: e1.ts and e2.ts.

e1.ts:

import { NextApiHandler } from 'next';
import analytics from '@/firebase/v2/analytics';

const handler: NextApiHandler = (req, res) => {
    analytics.setPaths('abc');
    return res.status(201).end();
};
export default handler;

and e2.ts:

import { NextApiHandler } from 'next';
import analytics from '@/firebase/v2/analytics';

const handler: NextApiHandler = (req, res) => {
    return res.status(200).json(analytics.getAll());
};
export default handler;

Now even when I add the data by hitting /api/e1 since the import instantiates a fresh class in e2, I fail to retrieve the data from /api/e2. How can I achieve my use case for this?

I also tried using static instance but that doesn't work as well. Can someone help me in finding a solution to this?

CodePudding user response:

In this article written by the Next.js team, if you go down to the section where they instantiate a PrismaClient, to not have a new instance in development, they use the global object, like so:

class Analytics {
  //...
}

let analytics: Analytics;

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

export default analytics;
  • Related