User accounts #

A user represents an identity within the server. Every user is registered and has a profile for other users to find and become friends with or join groups and chat.

A user can own records, share public information with other users, and authenticate via a variety of different social providers.

The system owner identity is represented by a user account with a nil UUID (00000000-0000-0000-0000-000000000000).

Fetch account #

When a user has a session you can retrieve their account. The profile contains a variety of information which includes various “linked” social providers.

Client
1
2
curl -X GET "http://127.0.0.1:7350/v2/account" \
  -H 'authorization: Bearer <session token>'
Client
1
2
3
4
const account = await client.getAccount(session);
const user = account.user;
console.info("User id '%o' and username '%o'.", user.id, user.username);
console.info("User's wallet:", account.wallet);
Client
1
2
3
4
var account = await client.GetAccountAsync(session);
var user = account.User;
System.Console.WriteLine("User id '{0}' username '{1}'", user.Id, user.Username);
System.Console.WriteLine("User wallet: '{0}'", account.Wallet);
Client
1
2
3
4
let account = await client.getAccount(session: session)
let user = account.user
debugPrint("User id:", user.id, "username:", user.username)
debugPrint("User wallet:", account.wallet)
Client
1
2
3
4
final account = await client.getAccount(session: session);
final user = account.user;
print('User id: ${user.id}, username: ${user.username}');
print('User wallet: ${account.wallet}');
Client
1
2
3
4
5
6
auto successCallback = [](const NAccount& account)
{
    std::cout << "User's wallet: " << account.wallet.c_str() << std::endl;
};

client->getAccount(session, successCallback);
Client
1
2
3
4
Account account = client.getAccount(session);
User user = account.getUser();
System.out.format("User id %s username %s", user.getId(), user.getUsername());
System.out.format("User wallet %s", account.getWallet());
Client
1
2
3
4
5
6
7
8
9
var account : NakamaAPI.ApiAccount = yield(client.get_account_async(session), "completed")

if account.is_exception():
    print("An error occurred: %s" % account)
    return

var user = account.user
print("User id '%s' and username '%s'." % [user.id, user.username])
print("User's wallet: %s." % account.wallet)
Client
1
2
3
4
5
6
7
8
9
var account : NakamaAPI.ApiAccount = await client.get_account_async(session)

if account.is_exception():
    print("An error occurred: %s" % account)
    return

var user = account.user
print("User id '%s' and username '%s'." % [user.id, user.username])
print("User's wallet: %s." % account.wallet)
Client
1
2
3
4
5
GET /v2/account
Host: 127.0.0.1:7350
Accept: application/json
Content-Type: application/json
Authorization: Bearer <session token>
Client
1
2
3
4
5
6
7
8
9
local result = client.get_account()

if result.error then
  print(result.message)
  return
end

local user = result.user
print(("User id '%s' and username '%s'."):format(user.id, user.username))

Some information like wallet, device IDs and custom ID are private but part of the profile is visible to other users.

Public FieldDescription
user.idThe unique identifier for the user.
user.usernameA unique nickname for the user.
user.display_nameThe display name for the user (empty by default).
user.avatar_urlA URL with a profile picture for the user (empty by default).
user.langThe preferred language settings for the user (default is “en”).
user.locationThe location of the user (empty by default).
user.timezoneThe timezone of the user (empty by default).
user.metadataA slot for custom information for the user - Read only from the client.
user.edge_countNumber of friends this user has.
user.facebook_idFacebook identifier associated with this user.
user.google_idGoogle identifier associated with this user.
user.gamecenter_idGameCenter identifier associated with this user.
user.steam_idSteam identifier associated with this user.
user.create_timeA timestamp for when the user was created.
user.update_timeA timestamp for when the user was last updated.
user.onlineA boolean that indicates whether the user is currently online or not.
Private FieldDescription
emailEmail address associated with this user.
devicesList of device IDs associated with this user.
custom_idCustom identifier associated with this user.
walletUser’s wallet - Read only from the client.
verify_timeA timestamp for when the user was verified (currently only used by Facebook).

User metadata #

You can store additional fields for a user in user.metadata which is useful to share data you want to be public to other users. We recommend using user metadata to store very common fields which other users will need to see. For example, use metadata to enable users to show biographical details if desired, or to display their character name, level, and game statistics.

For all other information you can store records with public read permissions which other users can find.

Metadata is limited to 16KB per user. This can be set only via the script runtime, similar to the wallet.

The following example showcases using user metadata to store a VIP status which is then used as part of a before join tournament hook which only allows VIP members to join.

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Assuming a user metadata structure as follows
const metadata = {
  vip: true
};

// Add a before hook to only allow VIP users to join the vip_only tournament
let BeforeJoinTournament: nkruntime.BeforeHookFunction<JoinTournamentRequest> = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, data: nkruntime.JoinTournamentRequest): nkruntime.JoinTournamentRequest | void {
  const account = nk.accountGetId(ctx.userId)

  // Only do the following checks if the tournament id is `vip_only`
  if (data.tournamentId != "vip_only") {
    return data;
  }

  // Only continue with the Join Tournament if the actioning user is a vip
  if (account.user.metadata["vip"]) {
    return data;
  }

  logger.warn("you must be a vip to join this tournament")
  return null;
};

// Register inside InitModule
initializer.registerBeforeJoinTournament(BeforeJoinTournament);
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Assuming a user metadata structure as follows
type UserMetadata struct {
	Vip bool `json:"vip"`
}

metadata := &UserMetadata {
  Vip: true,
}

// Add a before hook to only allow VIP users to join the vip_only tournament
if  err := initializer.RegisterBeforeJoinTournament(func(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, in *api.JoinTournamentRequest) (*api.JoinTournamentRequest, error) {
  userId, ok := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string)
  if !ok {
    logger.Error("invalid user")
    return nil, runtime.NewError("invalid user", 13)
  }

  // Get the user's metadata
  account, err := nk.AccountGetId(ctx, userId)
  if err != nil {
    logger.Error("error getting user account")
    return nil, runtime.NewError("error getting user account", 13)
  }

  // Only do the following checks if the tournament id is `vip_only`
  if in.TournamentId != "vip_only" {
    return in, nil
  }

  // Only continue with the Join Tournament if the actioning user is a vip
  var metadata UserMetadata
  if err := json.Unmarshal([]byte(account.User.GetMetadata()), &metadata); err != nil {
    logger.Error("error deserializing metadata")
    return nil, runtime.NewError("error deserializing metadata", 13)
  }

  if metadata.Vip {
    return in, nil
  }

  return nil, runtime.NewError("you must be a vip user to join this tournament", 7)
}); err != nil {
  logger.Error("unable to register before join tournament hook: %v", err)
  return err
}
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
-- Assuming a user metadata structure as follows
local metadata = {
    ["vip"] = true
}

-- Add a before hook to only allow VIP users to join the vip_only tournament
local function before_join_tournament(context, payload)
    local account = nk.account_get_id(context.user_id)

    -- Only do the following checks if the tournament id is `vip_only`
    if payload.tournament_id ~= "vip_only" then
        return payload
    end

    -- Only continue with the Join Tournament request if the actioning user is a vip
    if account.user.metadata["vip"] then
        return payload
    end

    nk.logger_error("you must be a vip user to join this tournament")
    return nil
end

nk.register_req_before(before_join_tournament, "JoinTournament")

Virtual wallet #

Nakama has the concept of a virtual wallet and transaction ledger. Nakama allows developers to create, update and list changes to the user’s wallet. This operation has transactional guarantees and is only achievable with the script runtime.

With server-side code it’s possible to update the user’s wallet.

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
local nk = require("nakama")
local user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"

local changeset = {
  coins = 10, -- Add 10 coins to the user's wallet.
  gems = -5   -- Remove 5 gems from the user's wallet.
}

local metadata = {
  game_result = "won"
}

local updated, previous = nk.wallet_update(user_id, changeset, metadata, true)
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
userID := "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
changeset := map[string]interface{}{
    "coins": 10, // Add 10 coins to the user's wallet.
    "gems":  -5, // Remove 5 gems from the user's wallet.
}
metadata := map[string]interface{}{
    "game_result": "won",
}
updated, previous, err := nk.WalletUpdate(ctx, userID, changeset, metadata, true)
if err != nil {
    logger.WithField("err", err).Error("Wallet update error.")
}
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let user_id = '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592';

let changeset = {
  coins: 10, // Add 10 coins to the user's wallet.
  gems: -5,   // Remove 5 gems from the user's wallet.
};

let metadata = {
  gameResult: 'won'
};

let result: nkruntime.WalletUpdateResult;

try {
    result = nk.walletUpdate(user_id, changeset, metadata, true);
} catch (error) {
    // Handle error
}

The wallet is private to a user and cannot be seen by other users. You can fetch wallet information for a user via Fetch Account operation.

Online indicator #

Nakama can report back user online indicators in two ways:

  1. Fetch user information to see if they are online. The user presence will be detected if they have an active socket connection to the server and did not set appearOnline=false.
  2. Publish and subscribe to user status presence updates. This will give you updates when the online status of the user changes (along side a custom message).

Fetch users #

You can fetch one or more users by their IDs or handles. This is useful for displaying public profiles with other users.

Client
1
2
curl -X GET "http://127.0.0.1:7350/v2/user?ids=userid1&ids=userid2&usernames=username1&usernames=username2&facebook_ids=facebookid1" \
  -H 'authorization: Bearer <session token>'
Client
1
2
3
4
5
const users = await client.getUsers(session, ["user_id1"], ["username1"], ["facebookid1"]);

users.foreach(user => {
  console.info("User id '%o' and username '%o'.", user.id, user.username);
});
Client
1
2
3
4
5
6
7
8
9
var ids = new[] {"userid1", "userid2"};
var usernames = new[] {"username1", "username2"};
var facebookIds = new[] {"facebookid1"};
var result = await client.GetUsersAsync(session, ids, usernames, facebookIds);

foreach (var u in result.Users)
{
    System.Console.WriteLine("User id '{0}' username '{1}'", u.Id, u.Username);
}
Client
1
2
3
4
5
6
7
8
let ids = ["userid1", "userid2"]
let usernames = ["username1", "username2"]
let facebookIds = ["facebookid1"]
let result = await client.getUsers(session: session, ids: ids, usernames: usernames, facebookIds: facebookIds)

for u in result.users {
    debugPrint("User id:", u.id, "username:", u.username)
}
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
final ids = ["userid1", "userid2"];
final usernames = ["username1", "username2"];
final facebookIds = ["facebookid1"];
final users = await client.getUsers(
  session: session,
  ids: ids,
  usernames: usernames,
  facebookIds: facebookIds,
);

for (final user in users) {
  print('User id: ${user.id}, username: ${user.username}');
}
Client
1
2
3
4
5
6
7
8
auto successCallback = [](const NUsers& users)
{
    for (auto& user : users.users)
    {
        std::cout << "User id '" << user.id << "' username " << user.username << std::endl;
    }
};
client->getUsers(session, { "user_id1" }, { "username1" }, { "facebookid1" }, successCallback);
Client
1
2
3
4
5
6
7
8
List<String> ids = Arrays.asList("userid1", "userid2");
List<String> usernames = Arrays.asList("username1", "username1");
String[] facebookIds = new String[] {"facebookid1"};
Users users = client.getUsers(session, ids, usernames, facebookIds).get();

for (User user : users.getUsersList()) {
  System.out.format("User id %s username %s", user.getId(), user.getUsername());
}
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var ids = ["userid1", "userid2"]
var usernames = ["username1", "username2"]
var facebook_ids = ["facebookid1"]
var result : NakamaAPI.ApiUsers = yield(client.get_users_async(session, ids, usernames, facebook_ids), "completed")

if result.is_exception():
    print("An error occurred: %s" % result)
    return

for u in result.users:
    print("User id '%s' username '%s'" % [u.id, u.username])
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var ids = ["userid1", "userid2"]
var usernames = ["username1", "username2"]
var facebook_ids = ["facebookid1"]
var result : NakamaAPI.ApiUsers = await client.get_users_async(session, ids, usernames, facebook_ids)

if result.is_exception():
    print("An error occurred: %s" % result)
    return

for u in result.users:
    print("User id '%s' username '%s'" % [u.id, u.username])
Client
1
2
3
4
5
GET /v2/user?ids=userid1&ids=userid2&usernames=username1&usernames=username2&facebook_ids=facebookid1
Host: 127.0.0.1:7350
Accept: application/json
Content-Type: application/json
Authorization: Bearer <session token>
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
local ids = { "userid1", "userid2" }
local usernames = { "username1", "username2" }
local facebook_ids = { "facebookid1" }
local result = client.get_users(ids, usernames, facebook_ids)

if result.error then
  print(result.message)
  return
end

local users = result.users

for _,user in ipairs(users) do
  print(("User id '%s' and username '%s'."):format(user.id, user.username))
end

You can also fetch one or more users in server-side code.

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
local nk = require("nakama")

local user_ids = {
  "3ea5608a-43c3-11e7-90f9-7b9397165f34",
  "447524be-43c3-11e7-af09-3f7172f05936"
}

local users = nk.users_get_id(user_ids)

for _, u in ipairs(users) do
  local message = ("username: %q, displayname: %q"):format(u.username, u.display_name)
  nk.logger_info(message)
end
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if users, err := nk.UsersGetId(ctx, []string{
    "3ea5608a-43c3-11e7-90f9-7b9397165f34",
    "447524be-43c3-11e7-af09-3f7172f05936",
}); err != nil {
    // Handle error.
} else {
    for _, u := range users {
      logger.Info("username: %s, displayname: %s", u.Username, u.DisplayName)
    }
}

Update account #

When a user is registered most of their profile is setup with default values. A user can update their own profile to change fields but cannot change any other user’s profile.

Client
1
2
3
4
5
6
7
curl -X PUT "http://127.0.0.1:7350/v2/account" \
  -H 'authorization: Bearer <session token>' \
  --data '{
    "display_name": "My new name",
    "avatar_url": "http://graph.facebook.com/avatar_url",
    "location": "San Francisco"
  }'
Client
1
2
3
4
5
await client.updateAccount(session, {
  display_name: "My new name",
  avatar_url: "http://graph.facebook.com/avatar_url",
  location: "San Francisco"
});
Client
1
2
3
4
const string displayName = "My new name";
const string avatarUrl = "http://graph.facebook.com/avatar_url";
const string location = "San Francisco";
await client.UpdateAccountAsync(session, null, displayName, avatarUrl, null, location);
Client
1
2
3
4
let displayName = "My new name"
let avatarUrl = "http://graph.facebook.com/avatar_url"
let location = "San Francisco"
await client.updateAccount(session: session, username: nil, displayName: displayName, avatarUrl: avatarUrl, langTag: nil, location: location)
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
final displayName = 'My new name';
final avatarUrl = 'http://graph.facebook.com/avatar_url';
final location = 'San Francisco';
await client.updateAccount(
  session: session,
  username: null,
  displayName: displayName,
  avatarUrl: avatarUrl,
  langTag: null,
  location: location,
);
Client
1
client->updateAccount(session, opt::nullopt, "My new name", "http://graph.facebook.com/avatar_url", opt::nullopt, "San Francisco");
Client
1
2
3
4
String displayName = "My new name";
String avatarUrl = "http://graph.facebook.com/avatar_url";
String location = "San Francisco";
client.updateAccount(session, null, displayName, avatarUrl, null, location);
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var display_name = "My new name";
var avatar_url = "http://graph.facebook.com/avatar_url";
var location = "San Francisco";
var update : NakamaAsyncResult = yield(client.update_account_async(session, null, display_name, avatar_url, null, location), "completed")

if update.is_exception():
    print("An error occurred: %s" % update)
    return

print("Account updated")
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var display_name = "My new name";
var avatar_url = "http://graph.facebook.com/avatar_url";
var location = "San Francisco";
var update : NakamaAsyncResult = await client.update_account_async(session, null, display_name, avatar_url, null, location)

if update.is_exception():
    print("An error occurred: %s" % update)
    return

print("Account updated")
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
PUT /v2/account HTTP/1.1
Host: 127.0.0.1:7350
Accept: application/json
Content-Type: application/json
Authorization: Bearer <session token>
{
  "display_name": "My new name",
  "avatar_url": "http://graph.facebook.com/avatar_url",
  "location": "San Francisco"
}
Client
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
local display_name = "Björn"
local avatar_url = "http://graph.facebook.com/avatar_url"
local lang_tag = ""
local timezone = ""
local username = ""
local location = "Stockholm"

local result = client.update_account(client, avatar_url, display_name, lang_tag, location, timezone, username)

if result.error then
  print(result.message)
  return
end

print("Account updated")

With server-side code it’s possible to update any user’s profile.

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
local nk = require("nakama")

local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521" -- some user's id.
local metadata = {}
local username = "my-new-username"
local display_name = "My new Name"
local timezone = nil
local location = "San Francisco"
local lang_tag = nil
local avatar_url = "http://graph.facebook.com/avatar_url"

local status, err = pcall(nk.account_update_id, user_id, metadata, username, display_name, timezone, location, lang_tag, avatar_url)

if (not status) then
  nk.logger_info(("Account update error: %q"):format(err))
end
Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521" // some user's id.
username := "my-new-username" // must be unique
metadata := make(map[string]interface{})
displayName := "My new name"
timezone := ""
location := "San Francisco"
langTag := ""
avatarUrl := "http://graph.facebook.com/avatar_url"

if err := nk.AccountUpdateId(ctx, userID, username, metadata, displayName, timezone, location, langTag, avatarUrl); err != nil {
    // Handle error.
    logger.Error("Account update error: %s", err.Error())
}

Delete account #

You can delete a user’s account on the server. This will remove all data associated with the user.

Client
1
2
curl -X DELETE "http://127.0.0.1:7350/v2/account" \
  -H 'authorization: Bearer <session token>'
Client
1
var account : NakamaAsyncResult = yield(client.delete_account_async(session), "completed")
Client
1
var account : NakamaAsyncResult = await client.delete_account_async(session)
Client
1
await client.DeleteAccountAsync(session);
Client
1
await client.deleteAccount(session: session)
Client
1
await client.deleteAccount(session: session);
Client
1
2
3
4
5
DELETE /v2/account
Host: 127.0.0.1:7350
Accept: application/json
Content-Type: application/json
Authorization: Bearer <session token>
Client
1
await client.deleteAccount(session);

Code snippet for this language Java/Android has not been found. Please choose another language to show equivalent examples.
Code snippet for this language C++/Unreal/Cocos2d-x has not been found. Please choose another language to show equivalent examples.
Code snippet for this language Defold has not been found. Please choose another language to show equivalent examples.

Related Pages