Adding new keys to the user object

Is there any way we can add a custom field to the user object once a user signs up and gets authenticated? For instance, I’d like to store a StripeID key-value pair in the auth0 object. Thanks!

Hi @ac98,

Welcome to the Community!

For adding things such as external IDs related to a user, you can use metadata on the user object. There are two types of metadata associated with a user: app metadata and user metadata. App metadata is application-specific (e.g. storing a flag that indicates to the app that the user has paid for something sold within the app). User metadata is for things like contact preferences or other data that is true across multiple apps.

You can read more about metadata here:

For your use case, it sounds like app metadata might be preferred. You can add metadata in a rule:

function(user, context, callback){
  user.user_metadata = user.app_metadata || {};
  // update the app_metadata that will be part of the response
  user.app_metadata.stripeID = 'abc123';

  // persist the app_metadata update
  auth0.users.updateUserMetadata(user.user_id, user.app_metadata)
    .then(function(){
      callback(null, user, context);
    })
    .catch(function(err){
      callback(err);
    });
}

For some reason, when I console.log(user), I do not see the field user_metadata even though the user_metadata field is filled in when I look at a particular user in User Management > Users. Is there any way that I can choose which attributes/keys get returned when I access the user object because it seems like I’m currently only getting a subset? I only see email, email_verified, name, nickname, picture, sub, and updated_at as accessible keys/attributes when I print a user object on the front-end, but would also like user_metadata

It sounds like you need to add the user metadata to the ID Token so that your frontend app can read it:

function(user, context, callback){
  user.user_metadata = user.app_metadata || {};
  // update the app_metadata that will be part of the response
  user.app_metadata.stripeID = 'abc123';

  const namespace = 'https://YOUR_APP_URL';
  context.idToken[namespace + '/app_metadata'] = user.app_metadata;

  // persist the app_metadata update
  auth0.users.updateUserMetadata(user.user_id, user.app_metadata)
    .then(function(){
      callback(null, user, context);
    })
    .catch(function(err){
      callback(err);
    });
}

Be sure to update the namespace to your own URL. A namespace is required for custom claims so that the claim does not collide with others.

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