How to use Elasticsearch from a SPA?

I have been wondering what is the best practice when wanting to query Elasticsearch directly from browser javascript. E.g. such as a React/VueJS/Angular application.

I hoped that it would be possible to use a standard oauth token, but from reading the documentation Elasticsearch only supports the Relaying Party role (with the addition of a facilitator service account) and not a Resource Server role. This causes a number of issues with a typical SPA architecture, which normally its self would be the Relaying Party/Client.

I was thinking that there are two options:

  1. Create a back end API that queries Elasticsearch and returns the results to the browser. This feels like a waste of effort, but would work and be more secure.
  2. Allow anonymous read access to specific indices. This is sub optimal as its not always the case that anonymous access is acceptable.

Is there a better solution?

From a security perspective you should consider Elasticsearch the same as a SQL database (think MySQL and Postgres), which also should not be exposed to the internet at any time.

The middleware you are talking in between is IMO a good additional security layer, as you can write the search queries on that component instead of just accepting blindly any user supplied JSON (that could contain arbitrary complex queries).
Also, such a middleware would allow you later on, to modify the query without the user noticing - think of boosting search results you get a higher commission on.

Hope this helps as a start.


Thanks, you make some good points :slight_smile:

Oh, one more thing. You might want to take a look at Elastic App Search, which is exactly providing a simplified middleware already and also allows you to access that middleware directly via the browser. You can try that out via Elastic Cloud, or give it a test run locally!

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.