Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Access Custom User Data - Node.js SDK

On this page

  • Before You Begin
  • Read Custom User Data
  • Write to Custom User Data with a MongoClient

You can store arbitrary custom data about your users with Atlas App Services. For example, you might store a user's preferred language, date of birth, or local timezone. Before writing and reading this data, you must enable custom user data in the backend. To learn more, see Enable Custom User Data.

To use custom user data, you must first enable custom user data in App Services:

  1. Create an App.

  2. Enable custom user data.

  3. Create a user to apply custom data to.

You retrieve custom user data in the customData property of the User object:

const customUserData = app.currentUser.customData;
console.log(customUserData);

App Services does not immediately update the value of the User.customData when underlying data changes. Instead, App Services fetches the most recent version of custom user data whenever a user refreshes their access token or when you explicitly call refreshCustomData(), which ensures your app has the latest custom user data.

const updatedCustomUserData = await user.refreshCustomData();
console.log(updatedCustomUserData);

Note

The customData field of the user object is read-only from a Node application.

Using standard CRUD operations through the MongoDB Atlas service and a mongoClient, you can access a user's custom data. The following example updates a user's custom data to alter the user's favoriteColor to pink.

// A user must be logged in to use a mongoClient
const user = app.currentUser;
const mongo = user.mongoClient("mongodb-atlas");
const collection = mongo.db("custom-user-data-database").collection("custom-user-data");
// Query for the user object of the logged in user
const filter = { userId: user.id};
// Set the logged in user's favorite color to pink
const update = { $set: { favoriteColor: "pink" }};
// Insert document if it doesn't already exist
const options = { upsert: true };
const result = await collection.updateOne(filter, update, options);

Note

To modify the custom data field from a client or user function, write permission to the collection in which custom data is stored must be configured. If you prefer to restrict client write access to custom data from your application, you can still modify the object from a system function.

Back

Authenticate Users

Next

User Metadata