Tips for fixing a server error when using NextJS and Sanity
3 replies
Last updated: Mar 5, 2022
H
Hi there 🙂 Any tips for what causes this error message?I’m using NextJS and Sanity.
Server Error
Error: Error serializing
Server Error
Error: Error serializing
.artistsreturned from
getServerSidePropsin “/exhibitions/[slug]“.Reason:
undefinedcannot be serialized as JSON. Please use
nullor omit this value.
Feb 24, 2022, 4:09 PM
R
Can you post your getServerSideProps code? It's probably an error with how you are fetching data and then returning said data as props to your component.
For example, if your make an api request and the data returned is undefined, you shouldn't allow the function to return that undefined value. You could use an expression to make sure the prop returns "null" instead of undefined.
For example, if your make an api request and the data returned is undefined, you shouldn't allow the function to return that undefined value. You could use an expression to make sure the prop returns "null" instead of undefined.
export async function getServerSideProps() { const postData = await fetch('some/api/url') return { props: { post: postData || null }, } }
Feb 24, 2022, 5:10 PM
H
Thanks for your message
user F
, here is my code:import { sanityClient } from "../../sanity"; const Exhibition = ({ title }) => { return <h1>{title}</h1>; }; export const getServerSideProps = async (pageContext) => { const pageSlug = pageContext.query.slug; const query = `*[ _type == "exhibition" && slug.current == $pageSlug] [0]{ title, artists[]{ ..., artist->{ name, slug, image, bio, } }, mainImage, categories->{ category, }, startDate, endDate, images[]{ ..., }, text, guide, mediaAndDownloads, }`; const exhibition = await sanityClient.fetch(query, { pageSlug }); if (!exhibition) { return { props: null, notFound: true, } } else { return { props: { title: exhibition.title, artists: exhibition.artists, mainImage: exhibition.mainImage, categories: exhibition.categories, startDate: exhibition.startDate, endDate: exhibition.endDate, images: exhibition.images, text: exhibition.text, guide: exhibition.guide, mediaAndDownloads: exhibition.mediaAndDownloads, }, }; } }; export default Exhibition;
Feb 24, 2022, 5:20 PM
H
Many thanks
user E
this was very helpful 🙂Mar 5, 2022, 2:15 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.