Sonson123
Sonson123

Reputation: 11437

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:

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?

Upvotes: 12

Views: 15011

Answers (1)

fatihpense
fatihpense

Reputation: 653

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");
  }

Upvotes: 2

Related Questions