# How to fix error serializing Date object JSON in Next.js

> Learn why Next.js throws a JSON serializable error when getServerSideProps returns a Date object, and how to fix it with JSON.parse(JSON.stringify(data)).

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-05-08 | Topics: [Next.js](https://flaviocopes.com/tags/next/) | Canonical: https://flaviocopes.com/nextjs-serialize-date-json/

If you've used [Next.js](https://flaviocopes.com/nextjs/) with a database you've surely ran into an issue like this.

You fetch some data in `getServerSideProps()` or `getStaticProps()`, for example like this with [Prisma](https://flaviocopes.com/prisma/):

```js
export async function getServerSideProps() {
  let cars = await prisma.car.findMany()

  return {
    props: {
      cars,
    },
  }
}
```

Now if the database table has a field that contains a date, that's converted to a `Date` object in [JavaScript](https://flaviocopes.com/javascript/) and you'll get an error like this:

![Next.js server error showing Date object cannot be serialized as JSON in getServerSideProps](https://flaviocopes.com/images/nextjs-serialize-date-json/Screen_Shot_2022-05-06_at_10.14.12.png)

This is because you must return a [JSON](https://flaviocopes.com/json/)-serializable object. A `Date` object cannot be natively transformed into JSON.

In this case the solution can be as simple as this:

```js
export async function getServerSideProps() {
  let cars = await prisma.car.findMany()

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

  return {
    props: {
      cars,
    },
  }
}
```

This has the effect of converting the `Date` object to a string.

I like this solution because it's obvious, visible, and not intrusive.

Another solution is to use a library called `superjson` and its Next.js adapter `next-superjson`:

```js
npm install next-superjson superjson
```

and add it to `next.config.js`:

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
}

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

module.exports = withSuperjson()(nextConfig)
```

I found it on the James Perkins blog post [Dealing with Date objects in Next data fetching](https://www.jamesperkins.dev/post/next-date-type-data-fetching).

A similar error happens for example if you try to return a complex object like a Fetch response:

```js
export async function getServerSideProps() {
  const res = await fetch(...)

  return {
    props: {
      res
    },
  }
}
```

![Next.js server error showing Response object cannot be serialized as JSON in getServerSideProps](https://flaviocopes.com/images/nextjs-serialize-date-json/Screen_Shot_2022-05-06_at_10.18.04.png)

But in this case the fix is not that easy.

You need to first get the response text like 

```js
export async function getServerSideProps() {
  const res = await fetch(...)
  const data = await res.json() 

  return {
    props: {
      data
    },
  }
}
```
