Hooks #

All runtime code is evaluated at server startup and can be used to register functions called hooks.

You can register before hooks to intercept and act on client messages, after hooks to call a function after an event has been processed, and custom RPC hooks which can be called by clients.

There are multiple ways to register a function within the runtime, each of which is used to handle specific behavior between client and server. For example:

Server
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-- NOTE: Function arguments have been omitted in the example.

-- If you are sending requests to the server via the real-time connection, ensure that you use this variant of the function.
nk.register_rt_before()
nk.register_rt_after()

-- Otherwise use this.
nk.register_req_after()
nk.register_req_before()

-- If you'd like to run server code when the matchmaker has matched players together, register your function using the following.
nk.register_matchmaker_matched()

-- If you'd like to run server code when the leaderboard/tournament resets register your function using the following.
nk.register_leaderboard_reset()
nk.register_tournament_reset()

-- Similarly, you can run server code when the tournament ends.
nk.register_tournament_end()

-- If you'd like to run server code when the server receives a shutdown signal. The function is only invoked if config grace_period_sec > 0.
-- It won't be awaited to complete if it takes longer than grace_period_sec.
nk.register_shutdown()
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
// NOTE: All Go runtime registrations must be made in the module's InitModule function.
//       Function arguments have been omitted in the example.

// If you are sending requests to the server via the real-time connection, ensure that you use this variant of the function.
initializer.RegisterBeforeRt()
initializer.RegisterAfterRt()

// Otherwise use the relevant before / after hook, e.g.
initializer.RegisterBeforeAddFriends()
initializer.RegisterAfterAddFriends()
// (...)

// If you'd like to run server code when the matchmaker has matched players together, register your function using the following.
initializer.RegisterMatchmakerMatched()

// If you'd like to run server code when the leaderboard/tournament resets register your function using the following.
initializer.RegisterLeaderboardReset()
initializer.RegisterTournamentReset()

// If you'd like to run server code when the server receives a shutdown signal. The function is only invoked if config grace_period_sec > 0.
// It won't be awaited to complete if it takes longer than grace_period_sec.
initializer.RegisterShutdown()

// Similarly, you can run server code when the tournament ends.
initializer.RegisterTournamentEnd()
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
// NOTE: All JavaScript runtime registrations must be made in the bundle's InitModule function.
//       Function arguments have been omitted in the example.

// If you are sending requests to the server via the real-time connection, ensure that you use this variant of the function.
initializer.registerRtBefore()
initializer.registerRtAfter()

// Otherwise use the relevant before / after hook, e.g.
initializer.registerBeforeAddFriends()
initializer.registerAfterAddFriends()
// (...)

// If you'd like to run server code when the matchmaker has matched players together, register your function using the following.
initializer.registerMatchmakerMatched()

// If you'd like to run server code when the leaderboard/tournament resets register your function using the following.
initializer.registerLeaderboardReset()
initializer.registerTournamentReset()

// Similarly, you can run server code when the tournament ends.
initializer.registerTournamentEnd()

// If you'd like to run server code when the server receives a shutdown signal. The function is only invoked if config grace_period_sec > 0.
// It won't be awaited to complete if it takes longer than grace_period_sec.
initializer.registerShutdown();

Message names #

Provided here is a full list of server messages that can benefit from hooks.

If your runtime code is in Go, refer to the interface definition for a full list of hooks that are available in the runtime package.

Use the following request names for registering your Before and After hooks:

Request NameDescription
AddFriendsAdd friends by ID or username to a user’s account.
AddGroupUsersAdd users to a group.
AuthenticateCustomAuthenticate a user with a custom id against the server.
AuthenticateDeviceAuthenticate a user with a device id against the server.
AuthenticateEmailAuthenticate a user with an email+password against the server.
AuthenticateFacebookAuthenticate a user with a Facebook OAuth token against the server.
AuthenticateGameCenterAuthenticate a user with Apple’s GameCenter against the server.
AuthenticateGoogleAuthenticate a user with Google against the server.
AuthenticateSteamAuthenticate a user with Steam against the server.
BlockFriendsBlock one or more users by ID or username.
CreateGroupCreate a new group with the current user as the owner.
DeleteAccountDelete the current user’s account.
DeleteFriendsDelete one or more users by ID or username.
DeleteGroupDelete one or more groups by ID.
DeleteLeaderboardRecordDelete a leaderboard record.
DeleteNotificationsDelete one or more notifications for the current user.
DeleteStorageObjectsDelete one or more objects by ID or username.
GetAccountFetch the current user’s account.
GetUsersFetch zero or more users by ID and/or username.
HealthcheckA healthcheck which load balancers can use to check the service.
ImportFacebookFriendsImport Facebook friends and add them to a user’s account.
JoinGroupImmediately join an open group, or request to join a closed one.
KickGroupUsersKick a set of users from a group.
LeaveGroupLeave a group the user is a member of.
LinkCustomAdd a custom ID to the social profiles on the current user’s account.
LinkDeviceAdd a device ID to the social profiles on the current user’s account.
LinkEmailAdd an email+password to the social profiles on the current user’s account.
LinkFacebookAdd Facebook to the social profiles on the current user’s account.
LinkGameCenterAdd Apple’s GameCenter to the social profiles on the current user’s account.
LinkGoogleAdd Google to the social profiles on the current user’s account.
LinkSteamAdd Steam to the social profiles on the current user’s account.
ListChannelMessagesList a channel’s message history.
ListFriendsList all friends for the current user.
ListGroupsList groups based on given filters.
ListGroupUsersList all users that are part of a group.
ListLeaderboardRecordsList leaderboard records.
ListMatchesFetch a list of running matches.
ListNotificationsFetch a list of notifications.
ListStorageObjectsList publicly readable storage objects in a given collection.
ListUserGroupsList groups the current user belongs to.
PromoteGroupUsersPromote a set of users in a group to the next role up.
DemoteGroupUsersDemote a set of users in a group to a lower role.
ReadStorageObjectsGet storage objects.
UnlinkCustomRemove the custom ID from the social profiles on the current user’s account.
UnlinkDeviceRemove the device ID from the social profiles on the current user’s account.
UnlinkEmailRemove the email+password from the social profiles on the current user’s account.
UnlinkFacebookRemove Facebook from the social profiles on the current user’s account.
UnlinkGameCenterRemove Apple’s GameCenter from the social profiles on the current user’s account.
UnlinkGoogleRemove Google from the social profiles on the current user’s account.
UnlinkSteamRemove Steam from the social profiles on the current user’s account.
UpdateAccountUpdate fields in the current user’s account.
UpdateGroupUpdate fields in a given group.
WriteLeaderboardRecordWrite a record to a leaderboard.
WriteStorageObjectsWrite objects into the storage engine.

Names are case-insensitive. For more information, see apigrpc.proto.

For real-time before and after hooks, use the following message names:

Message NameDescription
ChannelJoinJoin a realtime chat channel.
ChannelLeaveLeave a realtime chat channel.
ChannelMessageSendSend a message to a realtime chat channel.
ChannelMessageUpdateUpdate a message previously sent to a realtime chat channel.
ChannelMessageRemoveRemove a message previously sent to a realtime chat channel.
MatchCreateA client to server request to create a realtime match.
MatchDataSendA client to server request to send data to a realtime match.
MatchJoinA client to server request to join a realtime match.
MatchLeaveA client to server request to leave a realtime match.
MatchmakerAddSubmit a new matchmaking process request.
MatchmakerRemoveCancel a matchmaking process using a ticket.
PartyCreateA client to server request to create a party.
PartyJoinA client to server request to join a party.
PartyLeaveA client to server request to leave a party.
PartyPromoteA client to server request to promote a party member.
PartyAcceptA client to server request to accept a party join request.
PartyRemoveA client to server request to remove a party member.
PartyCloseA client to server request to close a party.
PartyJoinRequestListA client to server request to list all join requests for a particular party.
PartyMatchmakerAddSubmit a new party matchmaking process request.
PartyMatchmakerRemoveCancel a party matchmaking process using a ticket.
PartyDataSendA client to server request to send data to a party.
StatusFollowStart following some set of users to receive their status updates.
StatusUnfollowStop following some set of users to no longer receive their status updates.
StatusUpdateSet the user’s own status.

Names are case-insensitive. For more information, have a look at realtime.proto.

Before hooks #

Any function may be registered to intercept a message received from a client and operate on it (or reject it) based on custom logic. This is useful to enforce specific rules on top of the standard features in the server, or to replace what would otherwise be an invalid input.

Input validation does not apply until after execution of any before hooks, meaning clients can send larger (or otherwise invalid) inputs than the server would normally allow so long as the before hook replaces the input with a valid one. For example, given custom authentication IDs must be between 6-128 bytes, if your external authentication provider returns a longer ID use a before hook to replace that input with a valid ID.

In Go, each hook will receive the request input as a struct containing the data that will be processed by the server for that request, if that feature is expected to receive an input. In Lua, the second argument will be the incoming payload containing data received that will be processed by the server. In JavaScript the payload is the fourth argument.

You must remember to return the payload at the end of your function in the same structure as you received it.

If you choose to return nil (Lua) or null|undefined (JavaScript) instead of the payload (or a non-nil error in Go) the server will halt further processing of that message. This can be used to stop the server from accepting certain messages or disabling/blacklisting certain server features.

An example use case would be to hook into chat messages to apply your own profanity filter.

After hooks #

Similar to Before hook you can attach a function to operate on a message. The registered function will be called after the message has been processed in the pipeline. The custom code will be executed asynchronously after the response message has been sent to a client.

The second argument is the “outgoing payload” containing the server’s response to the request. The third argument contains the “incoming payload” containing the data originally passed to the server for this request.

After hooks cannot change the response payload being sent back to the client and errors do not prevent the response from being sent.

RPC hooks #

Some logic between client and server is best handled as RPC functions which clients can execute. For this purpose Nakama supports the registration of custom RPC hooks.

The ID of your registered RPC can be used within client code to send an RPC message to execute the function on the server and return the result.

From Go runtime code, the result is returned as (string, error). From Lua runtime code, results are always returned as a Lua string (or optionally nil). From the JavaScript runtime code, results should always be a string, null or omitted (undefined).

Related Pages