12

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 Answer 1

2

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");
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I used globalThis instead. like a charm
I'd like to add a caveat to this solution. If you're developing with hot module replacement (e.g. using next dev), this will prohibit new code from being loaded. So if you were to change this to load "fonts/SomeOtherFont.ttf", it wouldn't change it, since your code says "only load it if it hasn't been loaded. The same is true for class instances (singleton pattern), where the first version of the class instance may be stored globally, so any later versions will never be instantiated, and new code won't run unless you restart the dev server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.