Next.js+Sanity中getServerSideProps序列化报错求助
Next.js + Sanity 服务端序列化错误解决方案
问题详情
控制台抛出序列化错误:
Uncaught Error: Error serializing .title returned from getServerSideProps in "/property/[slug]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.
终端显示客户端与服务端编译均成功,尝试用JSON.stringify处理仍未解决问题。以下是对应slug组件的getServerSideProps代码:
export const getServerSideProps = async (pageContext) => { const pageSlug = pageContext.query.slug const query = `*[_type == "property" && slug.current == $pageSlug][0]{ title, location, propertyType, mainImage, images, pricePerNight, beds, bedrooms, description, host->{ _id, name, slug, image }, reviews[]{ ..., traveller->{ _id, name, slug, image } } }` const property = await sanityClient.fetch(query, { pageSlug}) if (!property) { return { props: null, notFound: true, } } else { return { props: { title: property.title, location: property.location, propertyType: property.propertyType, mainImage: property.mainImage, images: property.images, pricePerNight: property.pricePerNight, beds: property.beds, bedrooms: property.bedrooms, description: property.description, host: property.host, reviews: property.reviews } } } } export default Property
问题根源
报错核心是:getServerSideProps返回的props中,.title字段值为undefined,而Next.js要求服务端返回的props必须是可序列化的JSON,undefined不属于合法的JSON值,因此触发序列化失败。
这种情况要么是Sanity查询返回的property对象里确实没有title字段,要么是该字段在Sanity文档中未被赋值。
解决方法
1. 为字段设置兜底默认值
在返回props时,给所有可能为undefined的字段设置null或对应类型的默认值,确保不会传入undefined:
return { props: { title: property.title ?? null, location: property.location ?? null, propertyType: property.propertyType ?? null, mainImage: property.mainImage ?? null, images: property.images ?? [], pricePerNight: property.pricePerNight ?? null, beds: property.beds ?? null, bedrooms: property.bedrooms ?? null, description: property.description ?? null, host: property.host ?? null, reviews: property.reviews ?? [] } }
??是空值合并运算符,仅当左侧值为null或undefined时才返回右侧值,能精准处理字段缺失的情况。
2. 自动过滤undefined属性
如果不需要保留值为undefined的字段,可以直接过滤掉这些属性:
const cleanProps = Object.fromEntries( Object.entries(property).filter(([_, value]) => value !== undefined) ) return { props: cleanProps }
这段代码会遍历property对象,移除所有值为undefined的属性,避免序列化报错。
3. 排查Sanity文档完整性
在getServerSideProps中添加日志,确认查询返回的property结构:
console.log('查询到的房源数据:', property)
运行项目后查看终端输出,确认title字段是否存在。如果确实缺失,需要检查Sanity后台对应的房源文档,补充title字段内容。
内容的提问来源于stack exchange,提问作者Anita
相关产品推荐
相关产品推荐

