Running an action at login that adds UUID to the user profile

I am trying to add a v4 UUID to each user at login. This after finding this is not possible at registration.
My first stage was to get the value to populate. I ended with this:


//add-uuid-to-app-metadata Action
exports.onExecutePostLogin = async (event, api) => {
const { v4: uuidv4 } = require(‘uuid’);
event.user.app_metadata.uuid = event.user.app_metadata.uuid || uuidv4();
api.user.setAppMetadata(“uuid”, event.user.app_metadata.uuid)
};


This works, but of course it changes the uuid value in the metadata every time the same user logs in.
I found some examples that used an “if exist” type logic to not change the uuid if already there.
I have been working with the code below:


//add-uuid-to-app-metadata Action
exports.onExecutePostLogin = async (event, api) => {
const { v4: uuidv4 } = require(‘uuid’);
const { uuid } = event.user.user_metadata;
// short-circuit if the user signed up already
if ( uuid ) {
return;
}
// first time login/signup
api.user.setUserMetadata(“uuid”, uuidv4);
return;
};


My ‘if’ statement is not valid. I have tried variations and looked at other examples.
Could someone with more experienced than I with the scripting see what I need to make this work?
Any help is appreciated.

Hi @moore.4708,

Welcome to the Auth0 Community!

Yes, I noticed that the if statement checks if the uuid object is true or false based on whether the user’s user_metadata has any data.

What we should be doing instead is checking if the event.user.user_metadata.uuid exists and then assigning a uuid if there is not one.

I have attached a revised version, which you can use. It will set a new uuid if the user was not previously assigned with one.

//add-uuid-to-user-metadata Action
exports.onExecutePostLogin = async (event, api) => {
  const { v4: uuidv4 } = require(‘uuid’);
  event.user.user_metadata.uuid = event.user.user_metadata.uuid || uuidv4(); 
  api.user.setUserMetadata("uuid", event.user.user_metadata.uuid)
};

Let me know if you have any questions!

Cheers,
Rueben

That worked first-try! Thanks, Rueben.

Hi @moore.4708,

I’m happy to hear that it worked on the first try!

Please feel free to reach out to us again if you have any additional questions.

Thanks,
Rueben