'Send error Status codes to front end from ApolloServer GraphQL

I have this simple Apollo Server GraphQL running on Node, i want that every time i get something like 401 or any other error that GQL gets from formatError, send that error status to Front End, because now FE always receives 200 even if there is an error

const gateway = new ApolloGateway({
  serviceList,
})

const server = new ApolloServer({
  gateway,
  formatError: (err: GraphQLError) => {
    return new ApolloError(err.message, err.extensions.code, err.extensions)
  },
})

I have now that every time error is thrown formatError will return that error object to FE but i need to change response status code also instead of that being 200 all the time.



Solution 1:[1]

In GraphQL documentation:

GraphQL, by design, does not use the same conventions from REST to communicate via HTTP verbs and status codes.

Said that then, You can create a plugin according to the established flow Link:

import { GraphQLRequestContext } from 'apollo-server-types'

export default async function({ response, errors }: GraphQLRequestContext) {
    if (errors?.length) {
        // @ts-ignore
        response.http.status = errors[0].extensions.code
    }
}

From the above, it's important to add the @ts-ignore statement because it's an optional response statement in the GraphQLRequestContext interface.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emmanuel Rodríguez Ramírez