How to use CORS in Apollo
This is for any soul out there trying to make Apollo work with CORS, you’re not alone…
A couple days ago I was finishing up a personal project using Apollo Client & Apollo Server, everything was working just fine until I deployed the project and boom I got a CORS error in production.
Now, I didn’t thought this was going to be a problem, CORS is widely known for giving us headaches but fixing those error is usually pretty straight forward. So there I was installing CORS only to realize that you can’t inject CORS to apollo-server, I also tried a few configurations that were supposed to work but didn't, so I was there, staring at my computer like
No biggie though, after a little research I found that I just needed to use apollo-server-express and inject CORS through a middleware.
Long story sort, I did that and it didn’t work either, and, after I few hours of suffering and trying (without luck) every configuration I found on StackOverflow, GitHub and every other site, I came up with the following solution:
Now, your configuration might vary a little depending on what you need for your project, maybe you don’t want to use the ‘*’ wildcard or you might only allow certain methods, but in any case, the core of it will probably remain the same and by the moment you make your deployment you should see that
I hope this article brings some light to any fellow developer that might be suffering as I did, and, If you have any doubt, don’t hesitate to contact me, I’ll be more than happy to help.