👀 See Sanity in action: Watch product demo now →

Best Way to Fetch Global Data with GROQ and Next.js

11 replies
Last updated: Apr 30, 2021
What is the best way to fetch “global” data in with GROQ and Next? Things like content in the header and footer and menu items.
Apr 30, 2021, 1:31 PM
I know Next.js doesn’t have a good solution for this yet
Apr 30, 2021, 1:31 PM
Apr 30, 2021, 1:32 PM
Is fetching it in
_app.js
not good practice? That's what I've been doing to fetch my
siteSettings
singleton (site name, og:image, nav items, etc), which feeds it into each page.
Apr 30, 2021, 3:33 PM
If you mean using
getInitialProps
, then I would say, no. Or perhaps, it depends. See https://nextjs.org/docs/advanced-features/custom-app for some caveats.
Apr 30, 2021, 3:36 PM
If 
getServerSideProps
 or 
getInitialProps
 is present in a page, Next.js will switch to render the page on-demand, per-request (meaning Server-Side Rendering ).
Apr 30, 2021, 3:37 PM
hmm
getInitialProps
seems to work fine with SSG (next build & export) for me
Apr 30, 2021, 3:44 PM
Does it run for each page you're exporting?
Apr 30, 2021, 3:46 PM
good question -- i'll add a debug statement to check that
Apr 30, 2021, 3:46 PM
I'm curious about that, too! If so, you should probably look into the solutions I suggested, in order to limit the amount of API calls, unless the data changes on a page-by-page basis.
Apr 30, 2021, 3:47 PM
😬 this is only a few of the logs lol. yeah, i'm definitely gonna use one of those solutions above, thanks for the heads up!
Apr 30, 2021, 3:52 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.