4

I am using Sanity.io as a backend, within Sanity I am handling the data for my main menu (parent/children object arrays).

Whilst I can fetch this data just fine, I want to do so via getStaticProps, as I'd like my site to remain entirely statically generated.

getStaticProps doesn't work in my layout.js file as it's not located in the "pages" directory. Nor does it work inside the _app.js file.

So currently Im having to fetch the menu within each page, and pass it as a prop into the Layout components (which has to be on every page now!), so that I can pass it from inside the Layout into the header component. As such, my page looks like this:

function Page({ menu }) {
  return (
    <Layout menu={menu}>
      <article>
         ...
      </article>
    </Layout>
  )
}

export const getStaticProps = async (context) => {
  const menu = await client.fetch(**menu query**);

  return {
    props: {
      menu,
    },
  };
}

I am well aware that the Layout component should be situated inside the _app.js file instead, and that is where I'd rather it were, but I can't

This is obviously a very convoluted way of doing it, but I see no other method currently outside of using getInitialProps within Layout, but as I understand it, this will involved SSR rather than SSG.

I spent quite some time researching but the best answer I've found so far is that allowing getStaticProps in the layout "will be allowed in the near future", alas this was some time ago...

Can anybody point me in the right direction? It seems crazy to have to include the layout on each page rather than have it on every page in the app, just so that I can get data into the header component at build time.

2
  • So isn't no option to fetch on mount in Layout, even if it's just one time? Sep 19, 2022 at 6:46
  • For my purposes, no, only because I'd like the data to be present with OR without javascript being enabled. I realise 99.9% of users are going to have JS enabled. But when it comes to search engines crawling, more will get crawled, quicker if javascript isn't required to fetch any data integral to the site structure.
    – richtea
    Sep 19, 2022 at 13:52

1 Answer 1

1

Although I still haven't found a native solution to this which doesn't involve fetching the menu data in getStaticProps on every page and passing it up the tree to the Layout -> Header.

I did come across a guide to a Node based solution from Brewhouse digital, NextJS getStaticProps With Components which is pretty cool. Basically you can just create a "pre-build" process which is executed before the build, it fetches the data from your endpoint and stores it locally in a JSON file. You can then read that JSON file directly into your Layout or Header component for example.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.