
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI can see the issue in your code! There are actually two problems causing the undefined values:
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.
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:
context.params to get the slug from the URL&& slug.current == $slug to get the specific post[0] to get the first (and only) result instead of an arrayThis should resolve your undefined issues!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store