Sitecore Nextjs Error serializing .componentProps[“b53f473e-4cf1-4570-b6e5-aa46c9872634”].fields.title returned from getStaticProps

We have a Nextjs based Sitecore headless solution with Sitecore Experience Edge deployed to Vercel. We are prerendering most used pages during build to make sure they are always available even after a deploy so that even the first user who hits the page does not have to wait a few seconds to see it.


Our build to Vercel starting failing today with this strange error

Error occurred prerendering page "/en/contact-us". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Error serializing .componentProps["b53f473e-4cf1-4570-b6e5-aa46c9872634"].fields.title returned from getStaticProps in "/[[…path]]".
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

As you can see the error is pretty general and does not give you much idea about which component it might have come from. Initially I thought "b53f473e-4cf1-4570-b6e5-aa46c9872634" is an item or field ID and I should be able to look it up in Sitecore but that was not the case.

I knew that this is caused by content and could have fixed it through content but I wanted to apply a code fix so that I can prevent future cases like this without having to worry about content.

Steps to debug

I followed these steps to debug the issue

  1. Since it was happening on a particular page which I did not had in my local Sitecore instance so I packaged the page with components from that environment to local Sitecore.
    Tip: You can right click on an item and go to Scripts -> Packaging -> Quick Download Tree as Package
  2. Once I installed the download package I was able to produce it on local but still not able to figure out which component was causing it. The field name was so generic that it was used in almost all the components.
  3. I added console.log for props.componentProps inside getStaticProps in […path].tsx
    console.log('componentProps: ', props.componentProps);
  4. Once I figured out the component and fields, the fix was pretty easy as I had to ensure that the field returns null when undefined by adding ?? null
return {
    fields: {
	  ...
      title: componentBlock?.datasource?.title?.jsonValue ?? null,
	  ...
    },
    contentType: rendering?.params?.ImageShape ?? null,
  };

Keywords:
sitecore, nextjs, error, serialization, componentprops, getstaticprops, vercel, prerendering, json, debugging, sitecore experience edge, headless cms, build failure, web development, javascript, code fix, content management, console log, props, undefined, null, serialization error, sitecore packaging, sitecore tips, sitecore debugging

Hashtags:
#hashtags: #Sitecore #Nextjs #ErrorHandling #Serialization #ComponentProps #getStaticProps #Vercel #PreRendering #JSON #Debugging #HeadlessCMS #WebDevelopment #JavaScript #CodeFix #ContentManagement #ConsoleLog #Undefined #Null #SitecoreExperienceEdge