Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: Initialize an object once

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?

like image 862
Sonson123 Avatar asked Mar 18 '26 13:03

Sonson123


1 Answers

There is a relevant discussion here https://github.com/vercel/next.js/discussions/15054

But I would just use:

  if (!global.font) {
    global.font = fs.readFileSync("fonts/Somefont.ttf");
  }
like image 53
fatihpense Avatar answered Mar 21 '26 12:03

fatihpense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!