NextJS Server-Side Rendering Returns Empty Data from Sanity Client

0 replies
Last updated: Feb 18, 2022
Hello, I'm working on a local project, trying to return data from sanity. I am building an app with nextjs. I am trying to have nextjs pull data from sanity so it can be rendered server side. I have my request set up, and when I console log the request data it is just a blank line in the console. What am I doing wrong? I can only get it to return an empty object or a blank line.
If I set up an async function that isn't doing the next prerender, I get the data returned no problem. What am I doing wrong?


EDIT: Found my problem. I was calling my NextJS function in my component instead of on my page... Moving the logic to the page and passing the data as a prop to the component makes everything work
πŸ˜…
AI Update

Glad you found the solution! πŸŽ‰ This is actually a really common gotcha when first working with Next.js and Sanity together, especially with the App Router.

You've hit on an important distinction in how Next.js handles data fetching. When you call an async function that fetches data from Sanity using client.fetch inside a component, it runs in a different context than when you call it at the page level.

The Issue

In the Next.js App Router, pages (the page.tsx files) are React Server Components by default. When you fetch data at the page level, Next.js properly handles the async operation during the server-side render, waits for the data, and then renders your component with that data.

When you tried to fetch inside a component that was being rendered by that page, the timing and execution context likely caused issues - the component was probably trying to render before the data was available, or the fetch wasn't being properly awaited in the server component context.

The Solution (What You Did)

Moving your data fetching to the page level and passing it as props is exactly the right pattern:

// app/your-page/page.tsx
import { client } from '@/sanity/lib/client';

export default async function Page() {
  const data = await client.fetch(`*[_type == "yourType"]`);
  
  return <YourComponent data={data} />;
}

This ensures the data is fetched during server-side rendering and your component receives it as a prop, fully hydrated and ready to render.

Additional Tips

If you need to control caching behavior for your Sanity content, you can add these exports to your page:

export const revalidate = 60; // Revalidate every 60 seconds
// or
export const dynamic = 'force-dynamic'; // Always fetch fresh data

And if you're working with draft/preview content, check out Draft Mode for Visual Editing support!

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?