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.
I know Next.js doesn’t have a good solution for this yet
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.
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.
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 ).
hmm
getInitialProps
seems to work fine with SSG (next build & export) for me
Does it run for each page you're exporting?
good question -- i'll add a debug statement to check that
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.
😬 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!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?