NextJS: Initialize an object once

Viewed 2261

I use NextJS to generate a list of static pages.

All pages need one big static Javascript object which needs some minutes to initialize (it contains the result of parsing many other files).


const bigData = initializeBigData();   // <- called for every page, instead once

export async function getStaticProps({ params }) {
  return { bigData[params.slug] };  // ...
}

Unfortunately I cannot find a way to initialize this data object once. Instead the slow initializeBigData() runs every time when a page was created which makes the build very slow.

I've tried the following things:

  • Use a module as singleton
  • Use an ES6 class singleton
  • Use the npm package once
  • Reduce the build threads to 1: npm run build --threads=1

All these things change nothing, the long initializeBigData() is called for every single page when building the site.

If possible, I don't want to use a custom server.

How can an object get initialized only once in the build process of a NextJS project?

1 Answers
Related