Approaches to pulling global settings from Sanity into a Next.js app
Your approach with getInitialProps in _app.js and React Context is definitely a solid pattern! That's a common way people handle global settings from Sanity. Here are a few approaches that work well:
The Singleton Document Pattern
First, you'll want to set up your global settings as a singleton document in Sanity. This ensures you only have one instance of your settings document (like site colors, navigation, etc.) that can't be accidentally duplicated or deleted.
Frontend Fetching Approaches
1. Your _app.js + Context approach (totally valid!)
// _app.js
function MyApp({ Component, pageProps, settings }) {
return (
<SettingsContext.Provider value={settings}>
<Component {...pageProps} />
</SettingsContext.Provider>
)
}
MyApp.getInitialProps = async () => {
const settings = await client.fetch('*[_type == "siteSettings"][0]')
return { settings }
}This works great, though be aware that using getInitialProps in _app.js opts out of automatic static optimization for all pages.
2. Fetch per page (if using Next.js)
If you're using Next.js, you could fetch settings in each page's getStaticProps or getServerSideProps and pass them down. This keeps automatic static optimization but means fetching on every page:
export async function getStaticProps() {
const settings = await client.fetch('*[_type == "siteSettings"][0]')
return { props: { settings } }
}3. Fetch client-side on mount For less critical settings, you could fetch them client-side in a custom hook or context provider that runs on mount. This keeps your initial HTML lean but means a flash before settings load.
4. Bake into build (Next.js) If your settings rarely change, you could fetch them at build time and generate a static JSON file or environment variables that get bundled into your app.
Which to choose?
Your Context + getInitialProps approach is great if:
- Settings are needed on every page
- You want server-side rendering with settings available immediately
- You don't mind opting out of automatic static optimization
Consider the per-page approach if you want to keep static optimization or if only some pages need settings.
The key is making sure you're using a singleton document in Sanity so you're always querying a single, predictable settings document!
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.