Hi!
For our game we want users to add each other as friends, and we also want to avoid any user-generated content which includes setting their own username which others can see (we want to avoid the requirement to profanity filter or police this content as our game is available to all ages)
We have decided then to use a friend-code approach where two players can share their friend codes to add each other as friends - similiar to how Nintendo handle friends in the past.
In order to achieve this we are thinking the simplest way is to - when a user is created - set their account username as the randomly generated code. The code will be the format of xxx-xxxx-xxx, all numbers so a simple 10-digit number (hyphens are not necessary for input)
This leads me to my question - how do we ensure that friend codes are unique and there are no conflicts. The chances of two randomly generated 10-digit numbers being the same are astronomically slim but not impossible!
One approach I started to explore was have a storage object dictionary which is keyed with all generated friend codes.
- Read existing codes
- Generate random code
- Does code exist in dictionary?
– yes: generate a new one and repeat
– no: ok - assign this as the username
friendCode:= generateFriendCode()
usedFriendCodes := map[string]string{} // (read from nakama storage)
if _, ok := usedFriendCodes[friendCode]; ok {
// friend code already used
// return, try again
}
// Assign as used by this account
usedFriendCodes[friendCode] = accountId
This is fine but it leads to data duplication - an account is deleted then we need to also load this data and delete the friend code etc.
It seems the better approach would be to simply use the fact that usernames in Nakama must be unique. We can simply generate a friend code and assign it to their username by calling nk.AccountUpdateId and if this does not return an error then we know the code is unique. However, this leaves me slightly uncomfortable as my only way to determine what error has occurred is to query the message, which is plaintext english and could potentially change in future Nakama versions.
Is there a more reliable way to confirm the returned error? Is there a code I can query? Is there a different approach to this that I’m not seeing?
// Assign friendCode as their username
if err := nk.AccountUpdateId(ctx, "account-id", friendCode ...); err != nil {
// How to reliably confirm the error here is "Username is already in use."
// And not some other error which needs handling differently
}
// Example error:
{"level":"error","ts":"2026-01-06T11:13:35.309Z","caller":"server/core_account.go:257","msg":"Error updating user accounts.","error":"Username is already in use."}
- Versions: Nakama 3.35.1, Docker
- Server Framework Runtime language (If relevant) Go
Thank you!