Auth0 Metadata Is Undefined When Accessed in the Same Action

Overview

When an Auth0 Action sets metadata, the data remains unavailable immediately within the same Action due to a limitation with the metadata utility functions. To resolve this, use the local variable instead of attempting to access the metadata directly. When the Action prints or accesses the metadata using event.user.user_metadata or event.user.app_metadata, the values return as undefined, as demonstrated in the following sample code:

 

exports.onExecutePostLogin = async (event, api) => {

  let userName = "John";
  api.user.setUserMetadata("given_name", userName);
  console.log("given_name: ", event.user.user_metadata.given_name); //comes undefined

  let familyName = "Doe";
  api.user.setAppMetadata("family_name", familyName);
  console.log("family_name: ", event.user.app_metadata.family_name); //comes undefined

}
Applies To
  • Actions
  • setUserMetadata
  • setAppMetadata
Cause

This issue occurs due to a known limitation with how the metadata utility functions operate within the same Action.

Solution

The updated metadata variable becomes available in the subsequent Action after the previous Action sets the metadata. If the variable requires access for another purpose within the same Action, use the local variable that the code defines during the metadata utility function call.

Review the following code example to see how to properly use the local variables instead of the metadata values within the same Action:

 

exports.onExecutePostLogin = async (event, api) => {
  let userName = "John";
  let familyName = "Doe";

  // 1. Update the user profile in the backend
  api.user.setUserMetadata("given_name", userName);
  api.user.setAppMetadata("family_name", familyName);

  // 2. Define a namespace
  const namespace = "https://your-app-domain.com";

  // 3. Insert the claims into the ID Token using the local variables
  api.idToken.setCustomClaim(`${namespace}/given_name`, userName);
  api.idToken.setCustomClaim(`${namespace}/family_name`, familyName);
  
  // Do NOT use the metadata value in the same action like following
  // api.accessToken.setCustomClaim(`${namespace}/given_name`, event.user.user_metadata.given_name);
  // api.accessToken.setCustomClaim(`${namespace}/family_name`, event.user.app_metadata.family_name);
};

 

Setting metadata and accessing it in the same Auth0 Action using the event object is unsupported and returns an undefined value. 

 

NOTE: Auth0 batches multiple metadata updates into a single user profile update at the end of the trigger's execution, meaning data is not fully persisted simply by moving to the next Action. For more information on this behavior, review Manage User Metadata with the post-login Action Trigger.

Recommended content

No recommended content found...