Elasticsearch Search API: Are You Getting CORS?
This is just a small tip I want to share with you’ll guys.
One of the Elasticsearch strengths lies in the REST APIs that it exposes. These APIs can be used by the UI components and can be called directly to configure and access Elasticsearch features.
However, in case your UI components are not running on the same domain as your Elastricsearch instance, chances are that you’ll face a Cross-Origin Resource Sharing error. I’ve faced it while working on a VueJs application that queries directly my self-hosted Elasticsearch on a different domain and as you would’ve imagined it took me some precious minutes and I don’t want you to lose the same amount of time.
Well, the 2 tips I’m going to talk to you about are complementary. The first one will be in most cases mandatory and the second one will depend on your infrastructure service provider.
Let’s see together how they both can save you from this time-wasting issue.
1- Enable CORS from Elasticseach
Elasticsearch allows you to switch on Cross-Origin Ressource Sharing. To do so, you’ll need to add some parameters to the config file of Elasticsearch. Here they are:
http.cors.enabled : true
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Add those configurations to your elasticsearch.yml file, save it and restart Elasticsearch.
sudo systemctl restart elasticsearch
Unfortunately, for your testing projects, you’ll be facing even with these configurations, a real issue related to an SSL certificate. And that’s where the second option is the one you can rely on to move on.
2- Set up or use an existed proxy server
Let’s assume that you create a pure frontend web app that you deploy on AWS Amplify and you’ve got your self-hosted Elasticsearch instance that you’ll like to interact with after setting up all the above configurations. It’s mandatory to make requests only to secure the endpoint that also handles well CORS issues.
For that reason, you can use a tool like cors-everywhere. It has got a demo deployed on Heroku that lets you make some tests to be sure that you can reach your Elasticsearch without worries. You can also spin up your own Proxy server with Docker: https://hub.docker.com/r/redocly/cors-anywhere.
That’s all for this article. I just wanted to share these tips with you. Hope it helps you.
Till next time, take care.