How to populate persistent components with Sanity data in _app.js?
Good question! Since Next.js doesn't support getStaticProps in _app.js, you have a few solid patterns for handling shared data like headers across pages.
For Pages Router
The most common approach is to fetch your header data in each page's getStaticProps and pass it to the shared component. While this seems repetitive, you can create a reusable helper function:
// lib/getSharedData.js
import { client } from './sanity'
export async function getSharedData() {
const headerData = await client.fetch(`*[_type == "siteSettings"][0]{
logo,
navigation
}`)
return { headerData }
}Then in each page:
export async function getStaticProps() {
const { headerData } = await getSharedData()
const pageData = await client.fetch(/* your page query */)
return {
props: {
headerData,
pageData
}
}
}Pass headerData to your Header component from each page's props. Yes, it's a bit repetitive, but it keeps everything statically generated at build time.
For App Router (Next.js 13+)
If you're using the modern App Router, this gets much cleaner. You can fetch data directly in your root layout.tsx using React Server Components:
// app/layout.tsx
import { client } from '@/lib/sanity'
import Header from '@/components/Header'
async function getHeaderData() {
return await client.fetch(`*[_type == "siteSettings"][0]`)
}
export default async function RootLayout({ children }) {
const headerData = await getHeaderData()
return (
<html>
<body>
<Header data={headerData} />
{children}
</body>
</html>
)
}The layout fetches once per request and persists across page navigations. You can add export const revalidate = 3600 to control caching behavior.
Alternative: Global Singleton Pattern
Another approach is to structure your Sanity schema with a global settings singleton document that you query consistently. This makes your queries more predictable and your data structure clearer - you can read more about approaches to pulling global settings from Sanity into a Next.js app.
The App Router approach is definitely the most elegant if you're able to upgrade, but the helper function pattern works great for Pages Router projects and keeps your code DRY.
Show original thread19 replies
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.