Navigation

Authenticate a User

The Node SDK provides developers with a unified API to authenticate application users for any authentication provider. Users log in by providing authentication credentials for a given authentication provider and the SDK automatically manages authentication tokens and refreshes data for logged in users.

MongoDB Realm provides developers with an API to log application users in and out with any enabled authentication provider. Pass in a credentials object to specify the authentication provider info to the login methods.

The SDK provides the following methods for user authentication:

MethodUsage
App.logIn()Call App.logIn() to log a user in with a Realm.Credentials object for an enabled authentication provider. For example, running the script: "app.logIn(Realm.Credentials.emailPassword('<email>', '<password>'))" would log in a user created with an email/password authentication provider.
User.logOut()Call User.logOut() to log a user out, regardless of the authentication provider the user was registered using.

The Anonymous provider allows users to log in to your application with ephemeral accounts that have no associated information.

To log in, create an anonymous credential and pass it to App.logIn():

// Create an anonymous credential
const credentials = Realm.Credentials.anonymous();
try {
const user = await app.logIn(credentials);
console.log("Successfully logged in!", user.id);
return user;
} catch (err) {
console.error("Failed to log in", err.message);
}

The email/password authentication provider allows users to log in to your application with an email address and a password.

To log in, create an email/password credential with the user's email address and password and pass it to App.logIn():

// Create an email/password credential
const credentials = Realm.Credentials.emailPassword(
"joe.jasper@example.com",
"passw0rd"
);
try {
const user = await app.logIn(credentials);
console.log("Successfully logged in!", user.id);
return user;
} catch (err) {
console.error("Failed to log in", err.message);
}

The API key authentication provider allows server processes to access to access your app directly or on behalf of a user.

To log in with an API key, create an API Key credential with a server or user API key and pass it to App.logIn():

// Get the API key from the local environment
const apiKey = process.env?.realmServerApiKey;
if (!apiKey) {
throw new Error("Could not find a Realm Server API Key.");
}
// Create an api key credential
const credentials = Realm.Credentials.serverApiKey(apiKey);
try {
const user = await app.logIn(credentials);
console.log("Successfully logged in!", user.id);
return user;
} catch (err) {
console.error("Failed to log in", err.message);
}

The Custom Function authentication provider allows you to handle user authentication by running a function that receives a payload of arbitrary information about a user.

To log in with the custom function provider, create a Custom Function credential with a payload object and pass it to App.logIn():

// Create a custom function credential
const credentials = Realm.Credentials.function({ username: "mongolover" });
try {
const user = await app.logIn(credentials);
console.log("Successfully logged in!", user.id);
return user;
} catch (err) {
console.error("Failed to log in", err.message);
}

The Custom JWT authentication provider allows you to handle user authentication with any authentication system that returns a JSON web token.

To log in, create a Custom JWT credential with a JWT from the external system and pass it to App.logIn():

// Create a custom jwt credential
const jwt = await authenticateWithExternalSystem();
const credentials = Realm.Credentials.jwt(jwt);
try {
const user = await app.logIn(credentials);
console.log("Successfully logged in!", user.id);
return user;
} catch (err) {
console.error("Failed to log in", err.message);
}

The Facebook authentication provider allows you to authenticate users through a Facebook app using their existing Facebook account.

Important With Circle IconCreated with Sketch.Important
Enable the Facebook Auth Provider

To log a user in with their existing Facebook account, you must configure and enable the Facebook authentication provider for your application.

Important With Circle IconCreated with Sketch.Important
Do Not Store Facebook Profile Picture URLs

Facebook profile picture URLs include the user's access token to grant permission to the image. To ensure security, do not store a URL that includes a user's access token. Instead, access the URL directly from the user's metadata fields when you need to fetch the image.

You can use the official Facebook SDK to handle the user authentication and redirect flow from a client application. Once authenticated, the Facebook SDK returns an access token that you can send to your Node.js app and use to finish logging the user in to your app.

// Get the access token from a client application using the Facebook SDK
const accessToken = getFacebookAccessToken();
// Log the user in to your app
const credentials = Realm.Credentials.facebook(accessToken);
app.logIn(credentials).then((user: Realm.User) => {
console.log(`Logged in with id: ${user.id}`);
});

The Google authentication provider allows you to authenticate users through a Google project using their existing Google account.

Info With Circle IconCreated with Sketch.Note
Enable the Google Auth Provider

To authenticate a Google user, you must configure the Google authentication provider.

You can use the official Google SDK to handle the user authentication and redirect flow from a client application. Once authenticated, the Google SDK returns an access token that you can send to your Node.js app and use to finish logging the user in to your app.

// Get the access token from a client application using the Google SDK
const accessToken = getGoogleAccessToken();
// Log the user in to your app
const credentials = Realm.Credentials.google(accessToken);
app.logIn(credentials).then((user: Realm.User) => {
console.log(`Logged in with id: ${user.id}`);
});

The Apple authentication provider allows you to authenticate users through Sign-in With Apple.

Info With Circle IconCreated with Sketch.Note
Enable the Apple Auth Provider

To authenticate an Apple user, you must configure the Apple authentication provider.

You can use the official Sign in with Apple JS SDK to handle the user authentication and redirect flow from a client application. Once authenticated, the Apple JS SDK returns an ID token that you can send to your Node.js app and use to finish logging the user in to your app.

// Get the access token from a client application using the Apple JS SDK
const idToken: string = getAppleIdToken();
// Log the user in to your app
const credentials = Realm.Credentials.apple(idToken);
app.logIn(credentials).then((user: Realm.User) => {
console.log(`Logged in with id: ${user.id}`);
});

To log any user out, call the User.logOut() on their user instance.

Warning IconCreated with Sketch.Warning

When a user logs out, you can no longer read or write data in any synced realms that the user opened. As a result, any operation that has not yet completed before the initiating user logs out cannot complete successfully and will likely result in an error. Any data in a write operation that fails in this way will be lost.

// Log out the current user
await app.currentUser?.logOut();
// Log out a specific user by ID
if (app.currentUser) {
await app.allUsers[app.currentUser.id].logOut();
}
Give Feedback