NextJS getServerSideProps serialization error with undefined values from Sanity

3 replies
Last updated: Mar 5, 2022
Hi there πŸ™‚ Any tips for what causes this error message?I’m using NextJS and Sanity.

Server Error
Error: Error serializing
.artists
returned from
getServerSideProps
in β€œ/exhibitions/[slug]β€œ.Reason:
undefined
cannot be serialized as JSON. Please use
null
or omit this value.
AI Update

This error happens because Next.js can't serialize undefined values when passing props from getServerSideProps to your component. Next.js uses JSON to transfer data from server to client, and undefined isn't valid JSON.

In your case, the .artists field is coming back as undefined from your Sanity query, likely because:

  1. The field doesn't exist on the document - The exhibition you're querying doesn't have an artists field set
  2. There's a typo in your GROQ query - Check that you're requesting artists with the correct field name
  3. Missing comma in your query - Based on the thread you linked, syntax errors in GROQ queries can cause unexpected undefined values

How to fix it:

Option 1 - Use nullish coalescing in your return statement:

return {
  props: {
    ...exhibition,
    artists: exhibition.artists || null
  }
}

Option 2 - Spread the entire query response (cleaner approach):

return {
  props: { ...exhibition }
}

Option 3 - Filter out undefined values:

const cleanProps = Object.fromEntries(
  Object.entries(exhibition).filter(([_, v]) => v !== undefined)
);

return {
  props: cleanProps
}

Also check your GROQ query - Make sure there are no syntax errors. Common issues include:

  • Missing commas between fields
  • Incorrect reference syntax (should be fieldName-> for references)
  • Malformed projections

If you share your full query, I can help spot any syntax issues. The GROQ documentation is also helpful for validating query syntax.

Show original thread
3 replies
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.


export async function getServerSideProps() {
  const postData = await fetch('some/api/url')

  return {
    props: {
      post: postData || null
    },
  }
}
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;
Many thanks
user E
this was very helpful πŸ™‚

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?