Error: How to serialize data from getStaticProps : Next.js

22,423

Solution 1

Add JSON.stringify when calling an asynchronous function that returns an object.

Try modifying your getStaticProps function like this.

export async function getStaticProps() {
    const profiles = await getAllBusinessProfiles();
    const allProfiles = JSON.stringify(profiles)

    return {
        props: {
             allProfiles
        }
   };
}

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Source: MDN

Solution 2

I had this issue using Mongoose and Next.js.

To solve it: I switched from convert require to import then wrapped my result in JSON.parse(JSON.stringify(result));.

Good: import mongoose from 'mongoose';

Bad: const mongoose = require('mongoose');

Solution 3

I had the same issue when I was working with redux with next js and the reason was one of the fields in the default state I set it to undefined. Instead I used null:

const INITIAL_STATE = {
  products: [],
  loading: false,
  error: undefined,
  cart: [],
};

error:undefined was causing the error. Because "undefined" cannot be serialized:

export async function getStaticProps() {
    const allProfiles = await getAllBusinessProfiles();
    return {
      props: {
        allProfiles
      }
    };
  }

you are returning "allProfiles" which is the result of async getAllBusinessProfiles() which is either returning undefined, error or one of the fields of the returned object is undefined. "error" object is not serializable in javascript

Solution 4

I had the same serialization error when accessing a Vercel system environment variable in getStaticProps.

Using JSON.stringify did not do the trick, but String() worked. My code:

export async function getStaticProps() {
  const deploymentURL = String(process.env.NEXT_PUBLIC_VERCEL_URL);

  return {
    props: {
      deploymentURL,
    },
  };
}

Thanks to this GitHub issue for the inspiration

Share:
22,423
Adewale Perfect
Author by

Adewale Perfect

Updated on July 09, 2022

Comments

  • Adewale Perfect
    Adewale Perfect almost 2 years

    I'm working with Next.js, I tried accessing data but got this error:

    Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]".
    Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
    

    My code:

    import { getAllBusinessProfiles } from '../../lib/api';
    
    const Profile = ({ allProfiles: { edges } }) => {
        return ( 
            <>
              <Head>
                <title>Profile</title>
              </Head>
    
              <Hero />
    
              <section>
                {edges.map(({ node }) => (
                  <div key={node.id}>
                      <Link href={`/profile/${node.slug}`}>
                        <a> {node.businessInfo.name} </a>
                      </Link>
                  </div>
                ))}
              </section>
    
            </>
         );
    }
     
    export default Profile;
    
    export async function getStaticProps() {
        const allProfiles = await getAllBusinessProfiles();
        return {
          props: {
            allProfiles
          }
        };
      }
    

    getAllBusinessProfiles from api.js:

    const API_URL = process.env.WP_API_URL;
    
    async function fetchAPI(query, { variables } = {}) {
      const headers = { 'Content-Type': 'application/json' };
    
      const res = await fetch(API_URL, {
        method: 'POST',
        headers,
        body: JSON.stringify({ query, variables })
      });
    
      const json = await res.json();
      if (json.errors) {
        console.log(json.errors);
        console.log('error details', query, variables);
        throw new Error('Failed to fetch API');
      }
      return json.data;
    }
    
    export async function getAllBusinessProfiles() {
        const data = await fetchAPI(
          `
          query AllProfiles {
            businessProfiles(where: {orderby: {field: DATE, order: ASC}}) {
              edges {
                node {
                  date
                  title
                  slug
                  link
                  uri
                  businessInfo {
                    name
                    title
                    company
                    image {
                      mediaItemUrl
                      altText
                    }
                    highlight
                    phone
                    city
                    country
                    facebook
                    instagram
                    email
                    website
                    profiles {
                      profile
                      profileInfo
                    }
                    extendedProfile {
                      title
                      info
                    }
                  }
                }
              }
            }
          }
          
          `
        );
        return data?.businessProfiles;
    };
    

    What could be the error here? I used the getStaticProps method on Next.js but got the error above instead. Please, check. Thanks.

    The error: Server Error Error: Error serializing .profileData returned from getStaticProps in "/profile/[slug]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

    I don't know what could cause this though.

    • juliomalves
      juliomalves about 3 years
      Going to repeat what I mentioned in your last question: Some field in your allProfiles object is undefined which is not serializable as JSON so can't be returned from getStaticProps. Either convert those to null or omit them entirely.
    • Adewale Perfect
      Adewale Perfect about 3 years
      How will I fix it? Please
    • Dastan
      Dastan about 3 years
      did you fix it ?
    • Rom-888
      Rom-888 almost 3 years
      I have the same error. Could you fix it?
  • KeshavDulal
    KeshavDulal almost 3 years
    I was trying to export boolean value context.preview from getStaticProps and whenever I exited the preview mode, the value came undefined. I simply returned !!context.preview and the error was resolved.
  • Admin
    Admin about 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
  • Qwerty
    Qwerty about 2 years
    Is there a way how to unserialize the data automatically without having to call JSON.parse() on the props in the component manually?
  • Maxime Crtgn
    Maxime Crtgn almost 2 years
    It worked well for me using firestore. Thanks !