4

I'm building a web app with a Ruby on Rails backend and a ReactJS front-end. I'm using Algolia instantsearch.js for a search page and I want to use user keys to create a key when the page loads and remove access for that key when the user logs out. I also want them to expire after 2 hours.

All of this is going fine, but sometimes the newly-created user key doesn't get access to the index before the instantsearch client attempts to connect (weird, right?), causing the initial "search" to fail, an invalid key error to be returned by Algolia's server, and a blank results section. Type a search into the bar immediately after, though, and the key is accepted.

I've decided that when an invalid key error is returned, I would like the client to pause for a moment and try again. If that fails, I want an error message to appear to the user. This is also to solve the problem of a token expiring while the user is still using it - the message can just ask the user to refresh the page, avoiding the confusion of a suddenly unresponsive app.

Is there a way to do this with instantsearch? In standard Algolia search, you can add callbacks or specify like this:

index.search({
  filters: 'smartphone AND retina' // smartphone AND retina
}, function searchDone(err, content) {
  if (err) {
    console.error(err);
    return;
  }

  console.log(content);
});

But since instantsearch is supposed to "just work" it doesn't seem like I have control over the search function.

SearchResults is supposed to reveal the results and it work fine for getting hits from a successful search, but from what I can tell, they don't store the response code. It would be awesome if I was wrong about that, though.

This was suggested for getting callback-like behavior, but these solutions works on the render method, which I don't think happens if the entire client errors out from the start.

Community
  • 1
  • 1
AddAppend
  • 65
  • 5

1 Answers1

2

When you use add_user_key in Algolia, there's a small delay between the creation of the key and its propagation, hence the issue for your users. On loaded clusters, this can take a few seconds.

A way to check if the API key is ready to use would be to poll get_user_key_acl until it returns a 200 HTTP code.

We usually recommend using secured_api_keys instead.
Algolia's Secured API Keys are using an actual API key with a combination of parameters. They offer the same limiting capabilities than actual API keys (with the same security), but can be used with as many accounts as you want, dynamically changed without having to regenerate all API keys for all your customers, and finally are instantly available.

Jerska
  • 11,722
  • 4
  • 35
  • 54