Skip to content

Errors returned by getServerPage() can't be serialized to JSON #207

@mbrowne

Description

@mbrowne

In getServerSideProps(), it's not safe to return the object returned by getServerPage as-is. This is because errors in res.props.error can't be serialized to JSON.

This might not be a bug, but it does mean that you have to do your own error handling in every getServerSideProps function rather than handling that when you're rendering your component, or in pages/_app.tsx to keep your code more DRY. And it's confusing, because I thought that a property named props would be something you could safely return as the page props without modification.

The issue can be reproduced most easily by faking a GraphQL error:

import { GraphQLError } from 'graphql'
...
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
  ...
  res.props.error = [new GraphQLError('foo')]

This causes a next.js Server Error:

Error: Error serializing .error[0] returned from getServerSideProps in "/artists/[creatorId]/[lotId]".
Reason: object ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.

It would be great if the generated code returned an error prop that can be properly stringified to JSON instead of returning the ApolloError or GraphqlErrors objects directly. Or alternatively maybe generate a function you can optionally use to do the conversion, something like this:

    if (res.props.error) {
        return ssrMyQuery.pagePropsForErrorPage(res)
    }

...which would grab the error message(s) and return a plain object, e.g.:

{
  props: {
    error: {
      message: 'GraphqlError: foo'
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions