Navigation

Multi-User Applications - Node.js SDK

The Realm SDK automatically adds users to a device when they log in for the first time on that device. When a user logs in, they immediately become the application's active user.

Example

In the example below, a user with the email joe@example.com logs in and becomes the active user. Later, a user with the email emma@example.com logs in and becomes the active user.

const app = new Realm.App({ id: "myapp-abcde" });
// Log in as Joe
const joeCredentials = Realm.Credentials.emailPassword("joe@example.com", "passw0rd")
const joe = await app.logIn(joeCredentials);
// The active user is now Joe
assert(joe.id === app.currentUser.id);
// Log in as Emma
const emmaCredentials = Realm.Credentials.emailPassword("emma@example.com", "pa55word")
const emma = await app.logIn(emmaCredentials);
// The active user is now Emma, but Joe is still logged in
assert(emma.id === app.currentUser.id);

You can access a list of all user accounts on the device. This list includes all users that have logged in to the client app on a given device.

Example

In the example below, a developer prints out all the logged-in users on the device by looping through Realm.App.allUsers.

// Get a list of all Users
app.allUsers.forEach((user: Realm.User) => {
console.log(`User with id ${user.id} is ${user.isLoggedIn ? "logged in" : "logged out"}`);
});

You can remove all information about a user from the device and automatically log the user out.

Example

In the example below, the current user is removed from the device using the Realm.App.removeUser() method.

// Remove the current user from the device
const user = app.currentUser;
await app.removeUser(user);
// The user is no longer the active user
// The active user is now the logged in user (if there still is one) that was
// most recently active
assert(user.id !== app.currentUser?.id)
// The removed user is no longer on the device
assert(app.allUsers.find(({ id }) => id === user.id) === undefined);

You can quickly switch an app's active user to another logged-in user at any time.

Example

In the example below, the active user is initially switched to user1 using the Realm.App.switchUser() method. Later, the active user is switched to user2.

// Remove the current user from the device
const user = app.currentUser;
await app.removeUser(user);
// The user is no longer the active user
// The active user is now the logged in user (if there still is one) that was
// most recently active
assert(user.id !== app.currentUser?.id)
// The removed user is no longer on the device
assert(app.allUsers.find(({ id }) => id === user.id) === undefined);
Give Feedback