Search code examples
reactjsnetwork-programmingservergraphqlcors

How to reproduce and fix CORS errors


I build an application using React.js, GraphQL and Apollo.

After deployment, and visiting the page it works fine. But some users behind more restrictive network rules get a Failed to fetch error. After further investigating and some user sending me his console logs it seems they get a CORS error.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.domain.com:23116/graphql. (Reason: CORS request did not succeed). Status code: (null).

The port 23116 is where the API is running. I think that is why the error occurs because it thinks that these are 2 different sources.

  • How can I reproduce this? I want to debug and test solutions without asking a user every time "Does it work now?" I am using macOS in a normal home network enviroment.
  • How can I prevent this?

I already added app.use(cors()) to my server:

export async function startApolloServer(app: Express) {
  await apolloServer.start()

  app.use(cors())
  app.use(
    apolloEndpoint,
    json(),
    expressMiddleware(apolloServer, {
      context({ req }): Promise<GQLContext> {
        return GQLContext.fromUserOrTeacherToken(req.headers.authorization)
      }
    })
  )
}

Solution

  • Answering my own question here or rather giving an advice. This issue was mostly present in a strict network with firewall settings on, only enabling port 80 and 443.
    Because my server was running on a random port (f.e. 123456) the communication got blocked. I could reproduce the error then and debug further.

    Thanks to a co-worker we wrote a proxy and it seems to work fine now.