Next.js: Class instance across pages ssr

Viewed 184

I need to have access to App Insights (3rd-part library) object across different pages in Next.js app. The goal is to initialize object once and then use its methods in different pages. To check if object is the same in different pages I added date property with Date.now() value:

const appInsights = new ApplicationInsights({
        config: {
            instrumentationKey: <key>,
            /* ...Other Configuration Options... */
        },
    });
    appInsights.loadAppInsights();
    const ai = { ai: appInsights, date: Date.now() };

I was trying with Redux custom middleware (using redux-persist), but unfortunately every page visit triggers new object creation.

Do you know any solution that could help me?

1 Answers

I had the same problem. Next.js will recreate class instances in dev mode but will share them in the production build.

It seems like that next.js is rebuilding the source code of the pages on runtime regularly, so it will also recreate the class instance for these new builds.

Related