Generate new username immediately upon account creation

Hi, all!

I’ve created a server-side function to generate a unique random username for my players. I’m looking for a way to change their username immediately after they create their account. The goal is that they don’t ever see the initial Nakama-created username and instead see the username that I’m generating for them.

The first idea was to hook into an “account creation” event but, looking at the available hooks, I can’t find one that is truly suitable.

RegisterBeforeAuthenticateDevice or RegisterAfterAuthenticateDevice would change the username on every authentication. RegisterBeforeLinkDevice or RegisterAfterLinkDevice hooks would also potentially change the username multiple times, if users register more than one device.

Is there a hook that runs only once per account creation? If not, would it be possible to share a possible approach to handle this?

Thank you very much!

Hello @henriquejoyglitch

As part of the authentication functions there’s a returned param called created, this will only be true the first time the account is created, you can use it to ensure that you only apply your username change once for a newly created account in your after hook logic.

Hope this helps!

1 Like

Hey, @sesposito!

Yeah, I just noticed this shortly after I created the post!
Sorry about that :sweat_smile:

Thanks for the info!

Hey, @sesposito! Sorry to bother you again with this topic.

I’m noticing that if I use the RegisterAfterAuthenticateDevice hook, the Unity client still stores and uses the old (i.e. Nakama-created) username in the first session. I’m guessing the client stores the Username locally as soon as the account is created and the After hook runs after that. On subsequent sessions, the new Username is already shown.

I attempted to use the RegisterBeforeAuthenticateDevice hook, but it doesn’t give me access to the Session object and at that point it doesn’t seem like the User ID is even set (on the first session), so I can’t check if the account is being created.

Do you know of any way to set the Username so that the client already stores the new one?

Thank you!

EDIT: I can see that I could just run the GenerateUsername logic on the client and pass it as an argument to AuthenticateDeviceAsync in Unity on the first session, but I’d still like to know if there’s a way to do it server-side.

Generating the username client-side and sending it as part of the account creation/auth flow is an option and you could use a beforeHook to do username validation server-side to prevent any unwanted usernames from going through.

Another option is to call SessionRefreshAsync on the client after auth with the AccountUpdate on the after hook to force a token refresh which will give you a new session with the updated username from the after hook.

Hope this helps.