next-with-apollo: Allow error handling on the server

At the moment, errors are silently caught and ignored on the server when running getDataFromTree here. This means even if the graphql server sends back an error in query results, the NextJS server does not know this and will always return 200 which is bad for SEO.

It would be nice to be able to pass an error handler to the options to be able to handle this.

For example, this is what’s happening in my app:

// ComponentA.tsx

const ComponentA = () => {
  const { data, error } = useGetUserQuery();

  if( error ){
    // I want to throw an error with code "500" in here to be caught when running on the server
    // On the client, it shows an error page
    return <Error500 />
  }

  if( !data ||  !data.user ) {
    // I want to throw an error with code "404" in here to be caught when running on the server
   // On the client, it shows an error page
    return <Error404 />
  }
  ...
}

If withApollo uses a function passed in from the options, we can update the context so NextJS returns correct status code:

const MyAppWithApollo = withApollo(
  ({ initialState, headers }) => createApolloClient({ uri: process.env.GRAPHQL_ENDPOINT, initialState, ssrHeaders: headers }),
  {
    getDataFromTree,
    handleServerError: ( ctx, err ) => {
         ctx.res.statusCode = err.code; // This is an example, may need more checks in prod
    }
  }
)(MyApp);

Happy to create a PR if this makes sense 😃

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 4
  • Comments: 15 (6 by maintainers)

Most upvoted comments

That would be great, as now we can’t show a 404 page becuase we always get a 200 😕

thanks, any idea when we can merge it and re-publish a package? we’re currently using this and don’t want to use patch-package

ah i see, thanks just added, will have to think about the test since I’m mainly doing SSG

It does, @rajington. I tested the implementation locally and it worked for my use case!

I think if we passed the NextJS ctx here back to the handler, we’ll be able to change ctx.res.statusCode to 404 or 500. This will make NextJS return the same status code

EDIT: sorry just realised I can’t link to a line that’s not changed. Here’s the ctx I’m talking about:

const ctx = 'Component' in pageCtx ? pageCtx.ctx : pageCtx;

@rajington Seems cool! One thing: could be maybe useful to pass to the onError function, along with the error, the status code?