What is the best way to pass Realm App User credentials from browser to server?

I would like to use realm-web in the browser to simplify authentication. I also would like to use realm-web on the server to retrieve mongodb data and hide connection and query details.
What is the best way to pass Realm App User credentials from browser to server?
I am trying to experiment with apiKey, but I am not sure how to create an apiKey on the client:

// client
const app = new Realm.App({ id: '<ID>' });
await app.logIn(Realm.Credentials.emailPassword('user@domain.com', 'password'));
await app.currentUser?.apiKeys.create('testKey');
await app.currentUser?.apiKeys.enable('testKey');
const apiKey = await app.currentUser?.apiKeys.fetch('testKey');
// pass apiKey to the server?

and then pass it to the server:

// server
const clientKey = getKeyFromClient();
await app.logIn(Realm.Credentials.apiKey(clientKey));
 // invalid API key (status 401)

What is the right way to do that?

Hi again Ruslan,

Taken from the (Realm JS) documentation:

Store the API Key Value

The SDK only returns the value of the user API key when you create it. Make sure to store the key value securely so that you can use it to log in.

If you lose or do not store the key value there is no way to recover it. You will need to create a new user API key.

So, you need to store (and send to the server) the result of call to apiKeys.create(...) (more specifically the key property on the object returned).

With this change it looks like your code and approach would work. Please let us know how that goes.


Thank you, Kræn!

Going to try this approach.



Hi again. I’m sorry that I didn’t realise this before posting my reply, but it turns out the User constructor actually takes the arguments needed to construct and use a user from credentials transferred from a client to a server.

I’ve put together a small CodeSandbox to show this: https://codesandbox.io/s/realm-web-transfer-user-credentials-t1gxc (admittedly it gets a little harry around creation of the mockedServerStorage and serverSideApp, but I need this because two pieces of code is running the the same browser and will be simpler in your implementation)

Hope this helps.


This is amazing, @kraenhansen!

It’s just what we wanted to achieve!

Thanks for your help!



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