Adding metadata to user using management API

I am currently having a slight issue with registering users via the API and I think it’s down to our Pre-User Registration flow.

We currently have a Pre-User Registration flow that looks like this:

/**
 * @param {Event} event - Details about registration event.
 * @param {PreUserRegistrationAPI} api
 */
exports.onExecutePreUserRegistration = async (event, api) => {
  api.user.setUserMetadata("lang", event.transaction.locale)
}

This flow is supposed to add the user lang to the metadata so that we can use it for whatever we need.

My code to create a new user looks like this:

return $this->managementService->users()->create([
    'connection' => $this->connectionId,
    'email' => $user->getEmail(),
    'password' => substr(str_shuffle($permittedChars), 0, 16)
]);

When I add a user, then I get an error in the Auth0 logs that says:

TypeError on pre-user-registration: Cannot read property 'locale' of undefined

It makes sense, to me, that the flow is trying to add the lang, but because event.transaction is undefined, it fails. I’ve tried adding fields to my create body, but then it fails validation.

The one solution I see is to make a fallback for lang in the onExecutePreUserRegistration flow, but is there another way to do this in my PHP code?

Hi @bird,

Welcome to the Auth0 Community!

You can handle this case with a conditional in your Action and add the metadata directly via the management API.

For example:

/**
 * @param {Event} event - Details about registration event.
 * @param {PreUserRegistrationAPI} api
 */
exports.onExecutePreUserRegistration = async (event, api) => {
  if (event.transaction) {
    api.user.setUserMetadata("lang", event.transaction.locale)
  }
}

And when you register a user via the management API you can set "user_metadata":{"lang":"YOUR_LANG"} directly. It looks like you should be able to pass it in the body of the request: Auth0-PHP.