How do I make an Axios API call and store it as a custom claim using Actions?

Problem statement

I need to make a call to an external API to retrieve a response and set the API response as a custom claim in the Access/ID Token for my application.

Solution

To append the data from an external API response as a custom claim, you must use a Post-Login Action script. See below for an example using an Axios POST request:

exports.onExecutePostLogin = async (event, api) => {
  const axios = require('axios');
  
  const namespace = 'https://myapp-example.com';
  const url = 'https://YOUR_URL';
  const options = {
    headers: {
      'Content-Type': 'application/json'
    }
  };
  const data = {
    username: event.user.username, 
    email: event.user.email
  };
  var response = await axios.post(url, data, options);
  console.log(response.data);
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/CUSTOM_CLAIM_NAME_HERE`, response.data);
    api.accessToken.setCustomClaim(`${namespace}/CUSTOM_CLAIM_NAME_HERE`, response.data);
  }
};

Note that we need to save the response as a variable and await for the Axios post result before storing it as a custom claim in the token. If we do not wait for the response, we would observe undefined custom claims or claims that do not get appended to the token. This happens because Auth0 actions batch requests after the Action exits.

Reference materials