How to Fix "Error serializing date returned from getServerSideProps" Error in Next.js

Published Feb 9, 2022  ∙  Updated May 2, 2022

I’ve been trying to make a simple SELECT query to my database within getServerSideProps() in my Next.js application, but I kept running into the same error.

Suppose I have a User table in my database with this DateTime field called date.

date: 2022-02-09T16:03:25.786Z

Let’s run the following (simplified) code in /pages/view.js.

export const getServerSideProps = async ({ res }) => {
  const data = await prisma.user.findMany();
  return { 
    props: { 
      data 
    } 
  };
  // try-catch removed for simplification
};

It’ll result in this error.

Error serializing `.user.date` returned from `getServerSideProps` in "/view".
Reason: `object` ("[object Date]") cannot be serialized as JSON. 
Please only return JSON serializable data types.

This error appears because we are required to serialize any output of getStaticProps() and getServerSideProps() before sending it to the browser.

Fix the error using JSON.parse() and JSON.stringify()

A simple solution is to wrap our result in JSON.parse() and JSON.stringify().

return { 
  props: { 
    data: JSON.parse(JSON.stringify(data)) 
  } 
};

Fix the error by manually serializing fields

We can also write our own custom function to recursively serialize DateTime fields.

const serializeFields = obj => {
  let serialized = {};
  Object.keys(obj).forEach(key => {
    let val = obj[key];
    if (val !== null) {
      if (Array.isArray(val)) {
        // Loop through array
        val = val.map(item => serializeFields(item));
      } else if (typeof val === 'object' && typeof val.getMonth === 'function') {
        // Perform the serialization
        val = JSON.parse(JSON.stringify(val));
      } else if (typeof val === 'object') {
        // Recurse nested object
        val = serializeFields(val);
      }
    }
    serialized[key] = value;
  })
  return serialized;
}

We can then pass our data into this function.

return { 
  props: { 
    data: serialize(data) 
  } 
};

Fix the _id error in mongoose using lean()

This issue has appeared quite a bit for those retrieving data with the _id field from Mongo databases.

Adding lean() to the queries will return the object as a plain JavaScript object, removing the _id field.

const data = await User.find().lean();