View as Markdown

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:

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.
AuthenticateAppleAuthenticate a user with Apple Sign-In against the server.
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.
AuthenticateFacebookInstantGameAuthenticate a user with a Facebook Instant Game 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.
BanGroupUsersBan a set of users from a group.
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.
DeleteTournamentRecordDelete a tournament record.
DemoteGroupUsersDemote a set of users in a group to a lower role.
GetAccountFetch the current user’s account.
GetMatchmakerStatsGet matchmaker queue statistics.
GetSubscriptionGet a validated subscription for a user.
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.
ImportSteamFriendsImport Steam friends and add them to a user’s account.
JoinGroupImmediately join an open group, or request to join a closed one.
JoinTournamentAttempt to join an open tournament.
KickGroupUsersKick a set of users from a group.
LeaveGroupLeave a group the user is a member of.
LinkAppleAdd Apple Sign-In to the social profiles on the current user’s account.
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.
LinkFacebookInstantGameAdd a Facebook Instant Game 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.
ListFriendsOfFriendsList friends of the current user’s friends.
ListGroupsList groups based on given filters.
ListGroupUsersList all users that are part of a group.
ListLeaderboardRecordsList leaderboard records.
ListLeaderboardRecordsAroundOwnerList leaderboard records around a given owner.
ListMatchesFetch a list of running matches.
ListNotificationsFetch a list of notifications.
ListPartiesList parties.
ListStorageObjectsList publicly readable storage objects in a given collection.
ListSubscriptionsList validated subscriptions for a user.
ListTournamentRecordsList tournament records.
ListTournamentRecordsAroundOwnerList tournament records around a given owner.
ListTournamentsList tournaments.
ListUserGroupsList groups the current user belongs to.
PromoteGroupUsersPromote a set of users in a group to the next role up.
ReadStorageObjectsGet storage objects.
SessionLogoutLog out a session and optionally invalidate its tokens.
SessionRefreshRefresh a user’s session using a refresh token.
UnlinkAppleRemove Apple Sign-In from the social profiles on the current user’s account.
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.
UnlinkFacebookInstantGameRemove a Facebook Instant Game 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.
ValidatePurchaseAppleValidate and record an Apple IAP receipt.
ValidatePurchaseFacebookInstantValidate and record a Facebook Instant Game IAP receipt.
ValidatePurchaseGoogleValidate and record a Google IAP receipt.
ValidatePurchaseHuaweiValidate and record a Huawei IAP receipt.
ValidateSubscriptionAppleValidate and record an Apple subscription receipt.
ValidateSubscriptionGoogleValidate and record a Google subscription receipt.
WriteLeaderboardRecordWrite a record to a leaderboard.
WriteStorageObjectsWrite objects into the storage engine.
WriteTournamentRecordWrite a record to a tournament.

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

Listening for session changes #

The Authenticate* hooks fire only when a new session is created. To run logic on every token refresh (including for active, returning sessions), register a handler for the SessionRefresh request:

Real-time hooks #

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