Troubleshooting undefined data in Next.js and Sanity integration
I can see the issue in your code! There are actually two problems causing the undefined values:
1. Typo in function name
You wrote getServersideprops but it should be getServerSideProps (capital S in Server and capital P in Props). Next.js won't recognize your function with the incorrect casing, so it won't execute at all, leaving your props undefined.
2. Incorrect data structure handling
Your client.fetch(myquery) returns an array of posts (because of the *[_type == "post"] query), but you're treating it like a single object. You're trying to access result.title directly, but result is an array, not an object.
Here's the corrected code:
const myquery = `*[_type == "post"] {
title,
_id,
mainImage,
body
}`
export default function Post({posts}) {
console.log(posts); // This will now show your array of posts
return (
<div>
<h1>Post</h1>
{posts && posts.map(post => (
<div key={post._id}>
<h2>{post.title}</h2>
</div>
))}
</div>
);
}
export const getServerSideProps = async () => {
const result = await client.fetch(myquery)
return {
props: {
posts: result, // result is already the array of posts
}
}
}If you want to fetch a single post (which seems likely since this is a [slug].js file), you should modify your query to filter by the slug parameter:
export const getServerSideProps = async (context) => {
const { slug } = context.params;
const query = `*[_type == "post" && slug.current == $slug][0] {
title,
_id,
mainImage,
body
}`
const post = await client.fetch(query, { slug })
return {
props: {
post, // Now this is a single post object
}
}
}
export default function Post({post}) {
console.log(post); // Will show your single post
return (
<div>
<h1>{post?.title}</h1>
</div>
);
}The key differences:
- Fixed the function name capitalization
- Used
context.paramsto get the slug from the URL - Added a filter
&& slug.current == $slugto get the specific post - Added
[0]to get the first (and only) result instead of an array - Passed the slug as a parameter using GROQ parameters to prevent GROQ injection
This should resolve your undefined issues!
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.