Global place to fetch menu items in NextJs from getServerSideProps or getStaticProps

Viewed 3791

Is there any global place in Next.js to fetch menu-items(server-side) that I can pass to my Layout component.

Since, I can't do that in index.js as if somebody directly opens different route for eg: /about then the data will not be fetch.

I tried doing that in _app by implementing it's static getInitialProps method but I'm not sure if it's a good practice and also it will disable Automatic Static Optimization in pages without Static Generation.

Any suggestion?

2 Answers

getInitialProps is the old way of what you are doing to do. But getServerSideProps and getStaticProps will replace getInitialProps

getInitialProps seem to be deprecated soon https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

But getServerSideProps can't be used in _app for global data fetching for now. It will be introduced later. Until then, I think you have these options:

  1. Keep using getInitialProps and trade static optimization
  2. Get the menu items on the client side and render an activity indicator (a spinner?) until the data is ready.
  3. Add a getServerSideProps wrapper and a HoC like withMenuItem and wrap all pages and their getServerSideProps exports.

An example of the getServerSideProps HoC

const withGlobalData = (getStaticProps) => async (...props) => {
  const result = await getStaticProps(...props)

  const staticProps = result?.props || {}

  const global = { menuItems: ['home', 'about'] } // your global props

  return {...result, props: { ...staticProps, global }}
}
Related