question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

getServerSideProps Fails to Serialize Date Object

See original GitHub issue

Bug report

Describe the bug

When passing a date over the getServerSideProps boundary, it fails to serialize the Date object. Dates are serializable, so they should be allowed through.

To Reproduce

Attempt to pass a date time through the API, like so

page/index.tsx

const Component = () => {
    return <div>Hello</div>
}

export const getServerSideProps = async (ctx) => {
    const d = new Date();
    return { props: { d } }
}

export default Component

Expected behavior

Serializing occurs just fine

Screenshots

See Stack Trace

System information

  • OS: [e.g. macOS, Windows]
  • Browser (if applies) [e.g. chrome, safari]
  • Version of Next.js: [e.g. 6.0.2]
  • Version of Node.js: [e.g. 10.10.0]

Additional context

While crude, to not have to write complex logic to determine serializability, you could replace the offending method with

const canSerialize = (obj) => {
    try {
        JSON.stringify(obj);
        return false;
    } catch (e) {
        return false;
    }
}

Stack Trade:

SerializableError: Error serializing `.user.lastLogin` returned from `getServerSideProps` in "/dashboard".
Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.
    at isSerializable (/Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:9:7)
    at /Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:7:497
    at Array.every (<anonymous>)
    at isSerializable (/Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:7:304)
    at /Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:7:497
    at Array.every (<anonymous>)
    at isSerializable (/Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:7:304)
    at Object.isSerializableProps (/Users/jake/programming/Railway/frontend/node_modules/next/dist/lib/is-serializable-props.js:9:219)
    at Object.renderToHTML (/Users/jake/programming/Railway/frontend/node_modules/next/dist/next-server/server/render.js:356:42)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async DevServer.renderToHTMLWithComponents (/Users/jake/programming/Railway/frontend/node_modules/next/dist/next-server/server/next-server.js:660:26)
    at async DevServer.renderToHTML (/Users/jake/programming/Railway/frontend/node_modules/next/dist/next-server/server/next-server.js:807:28)
    at async DevServer.renderToHTML (/Users/jake/programming/Railway/frontend/node_modules/next/dist/server/next-dev-server.js:22:539)
    at async DevServer.render (/Users/jake/programming/Railway/frontend/node_modules/next/dist/next-server/server/next-server.js:552:22)
    at async Object.fn (/Users/jake/programming/Railway/frontend/node_modules/next/dist/next-server/server/next-server.js:402:17)

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

9reactions
AlexandraKleincommented, Oct 18, 2020

I’m having this issue when fetching data from Contentful on posts that have links to each other.

Re: https://github.com/vercel/next.js/blob/86160a5190c50ea315c7ba91d77dfb51c42bc65f/packages/next/lib/is-serializable-props.ts#L41

Stringifying using safe-json-stringify and reparsing fixes, but I’m hoping there is a more performant solution.

import safeJsonStringify from 'safe-json-stringify';
...

export async function getServerSideProps({ params, preview = false }) {
  const rawData = await getSlugPageProps(params.slug, 'product-page', preview);
  const stringifiedData = safeJsonStringify(rawData);
  const data = JSON.parse(stringifiedData);

  return {
    props: {
      data
    }
  };
}
7reactions
icflorescucommented, Apr 3, 2021

I stumbled across the same problem and got it working with by using the superjson-next plugin. See more here: https://github.com/blitz-js/superjson#using-with-nextjs

Read more comments on GitHub >

github_iconTop Results From Across the Web

`object` ("[object Date]") cannot be serialized as JSON. Please ...
According to NextJS API Docs getStaticProps return "should be a serializable object so that any props passed, could be serialized ...
Read more >
How to fix error serializing Date object JSON in Next.js
Learn why you get the JSON serializable error in Next.js when you return an object with a date and how to fix it....
Read more >
Dealing with Date objects in Next data fetching - James Perkins
Data fetching with dates in Next.js usually lead to a error serializing due to date timestamps. We can easily handle this in a...
Read more >
Prisma not working with next serversideprops : r/nextjs - Reddit
Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.
Read more >
getInitialProps - Data Fetching - Next.js
Data returned from getInitialProps is serialized when server rendering, similar to what JSON.stringify does. Make sure the returned object from ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found