/

How to Resolve JSON Serialization Error with Date Objects in Next.js

How to Resolve JSON Serialization Error with Date Objects in Next.js

In this article, we will discuss a common issue in Next.js when serializing Date objects to JSON and learn how to fix it.

If you have worked with Next.js and a database, you may have encountered this problem. When fetching data in the getServerSideProps() or getStaticProps() functions, you may receive an error when dealing with fields that contain a date value.

For example, let’s consider fetching data using Prisma:

1
2
3
4
5
6
7
8
9
export async function getServerSideProps() {
let cars = await prisma.car.findMany();

return {
props: {
cars,
},
};
}

If the database table has a field with a date value, it will be converted to a Date object in JavaScript. However, JSON serialization requires the object to be converted into a JSON-serializable format.

To fix this issue, you can simply convert the Date object to a string using JSON.stringify() and then parse it back using JSON.parse().

1
2
3
4
5
6
7
8
9
10
11
export async function getServerSideProps() {
let cars = await prisma.car.findMany();

cars = JSON.parse(JSON.stringify(cars));

return {
props: {
cars,
},
};
}

By converting the Date object to a string, you ensure that the object can be serialized as JSON.

Another solution is to use a library called superjson along with its Next.js adapter next-superjson. Follow these steps to implement it:

  1. Install the required packages:
1
npm install next-superjson superjson
  1. Add the following code to your next.config.js file:
1
2
3
4
5
6
7
8
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};

const { withSuperjson } = require('next-superjson');

module.exports = withSuperjson()(nextConfig);

This solution utilizes the superjson library, which provides enhanced JSON serialization capabilities for Next.js.

It’s worth mentioning that a similar error can occur when trying to return complex objects like a Fetch response.

1
2
3
4
5
6
7
8
9
export async function getServerSideProps() {
const res = await fetch(...);

return {
props: {
res,
},
};
}

To resolve this error, you need to retrieve the response text using res.json() before returning it.

1
2
3
4
5
6
7
8
9
10
export async function getServerSideProps() {
const res = await fetch(...);
const data = await res.json();

return {
props: {
data,
},
};
}

By extracting the JSON response data, you ensure that the object can be serialized properly.

In summary, when encountering JSON serialization errors with Date objects or complex objects in Next.js, you can address it by converting the object to a JSON-serializable format or by using libraries like superjson and its Next.js adapter next-superjson.

Tags: Next.js, JSON serialization, Date object, superjson, next-superjson, Fetch response