The runtime framework is essential to writing server-side logic for your games or apps. Use it to write code you would not want to run on client devices or the browser. The code you deploy with the server can be used immediately by clients, allowing you to change behavior on the fly and add new features faster. This code can be used to run authoritative logic or perform validation checks as well as integrate with other services over HTTPS.
This page will cover the key concepts and functionality available in the Nakama runtime framework.
Loading modules #
By default the server will scan all files within the
data/modules folder relative to the server file or the folder specified in the YAML configuration at startup. You can also specify the modules folder via a command flag when you start the server.
Files with the
.js extensions found in the runtime path folder will be loaded and evaluated as part of the startup sequence. Each of the runtimes has access to the Nakama API to operate on messages from clients as well as execute logic on demand.
index.js file. To change the name of the relative file path where the code will be loaded within the runtime path you can set it in the server YML or as a command flag.
This path must be relative to the default or set runtime path.
Go runtime #
The Go runtime looks for a Go plugin
.so shared object file.
To learn how you can generate this file with your custom Go runtime code follow see building the Go shared object.
Lua runtime #
The Lua runtime will interpret and load any
.lua files, including those in a subdirectory. These can be referenced as modules with relative paths.
Each Lua file represents a module and all code in each module will be run and can be used to register functions.
Runtime context #
All registered functions across all runtimes receive a
context as the first argument. This contains fields which depend on when and how the code is executed. You can extract information about the request or the user making it from the context:
If you are writing your runtime code in Lua, the
context will be a table from which you can access the fields directly. The Go runtime context is a standard
|A table of key/value pairs which are defined in the YAML configuration of the server. This is useful to store API keys and other secrets which may be different between servers run in production and in development.|
|The mode associated with the execution context. It’s one of these values: “run_once”, “rpc”, “before”, “after”, “match”, “matchmaker”, “leaderboard_reset”, “tournament_reset”, “tournament_end”.|
|The Nakama server version.|
|Query params that was passed through from HTTP request.|
|The user session associated with the execution context.|
|The user ID associated with the execution context.|
|The username associated with the execution context.|
|The user session expiry in seconds associated with the execution context.|
|The IP address of the client making the request.|
|The port number of the client making the request.|
|The match ID that is currently being executed. Only applicable to server authoritative multiplayer.|
|The node ID that the match is being executed on. Only applicable to server authoritative multiplayer.|
|Labels associated with the match. Only applicable to server authoritative multiplayer.|
|Tick rate defined for this match. Only applicable to server authoritative multiplayer.|
Go context #
The runtime context is distinct from the Go context. It is important that a
Context type be included in all server requests to avoid a potential overloading of the server with dead requests (i.e. requests from users who have since disconnected).
Inclusion of the
Context allows for the context cancellation - when a user’s HTTP connection to the server is closed - to be propagated across the entire chain of requests and avoid the processing and/or buildup of such dead requests.
Database handler #
The runtime includes a database object that can be used to access the underlying game database. This enables you to include custom SQL queries as part of your game design and logic.
The database handler has a limit on the number of available connections to the database. This can lead to slowed response time for your users along with other errors. To avoid such issues you must ensure that your custom SQL queries properly release the connection once finished with the relevant row(s).
db.Query(), you must call
row.Close() after you are finished with the database rows data.
db.QueryRowContext(), you must call either
row.Close() after you are finished with the database rows data.
A logger instance included in the server runtime enables you to write and access log messages in your server code using the following severities:
Nakama module #
The Nakama module is included in the code runtime built into the server. This module provides access to a range of functions for implementing custom logic and behavior.
See the function reference for your preferred language to learn about the available functions:
RPC functions #
Remote Procedure Calls (RPCs) let you call functions registered in your runtime code to operate on messages received from clients or execute custom logic on demand, for example a profanity filter for chat messages.
RPC functions can be called both from clients and through server-to-server calls.
All runtime code is evaluated at server startup and can be used to register functions - these functions are 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:
See Message Names for the full list of available hooks.
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 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
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.
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
null or omitted (undefined).
Server to server #
You can check if the context has a user ID to see if an RPC function is a client or server-to-server call. Server to server calls will never have a user ID. If you want to scope functions to never be accessible from the client just return an error if you find a user ID in the context.
See the server runtime examples.
Run once #
The runtime environment allows you to run code that must only be executed only once. This is useful if you have custom SQL queries that you need to perform or to register with third party services.
Message names #
|AddFriends||Add friends by ID or username to a user’s account.|
|AddGroupUsers||Add users to a group.|
|AuthenticateCustom||Authenticate a user with a custom id against the server.|
|AuthenticateDevice||Authenticate a user with a device id against the server.|
|AuthenticateEmail||Authenticate a user with an email+password against the server.|
|AuthenticateFacebook||Authenticate a user with a Facebook OAuth token against the server.|
|AuthenticateGameCenter||Authenticate a user with Apple’s GameCenter against the server.|
|AuthenticateGoogle||Authenticate a user with Google against the server.|
|AuthenticateSteam||Authenticate a user with Steam against the server.|
|BlockFriends||Block one or more users by ID or username.|
|CreateGroup||Create a new group with the current user as the owner.|
|DeleteAccount||Delete the current user’s account.|
|DeleteFriends||Delete one or more users by ID or username.|
|DeleteGroup||Delete one or more groups by ID.|
|DeleteLeaderboardRecord||Delete a leaderboard record.|
|DeleteNotifications||Delete one or more notifications for the current user.|
|DeleteStorageObjects||Delete one or more objects by ID or username.|
|GetAccount||Fetch the current user’s account.|
|GetUsers||Fetch zero or more users by ID and/or username.|
|Healthcheck||A healthcheck which load balancers can use to check the service.|
|ImportFacebookFriends||Import Facebook friends and add them to a user’s account.|
|JoinGroup||Immediately join an open group, or request to join a closed one.|
|KickGroupUsers||Kick a set of users from a group.|
|LeaveGroup||Leave a group the user is a member of.|
|LinkCustom||Add a custom ID to the social profiles on the current user’s account.|
|LinkDevice||Add a device ID to the social profiles on the current user’s account.|
|LinkEmail||Add an email+password to the social profiles on the current user’s account.|
|LinkFacebook||Add Facebook to the social profiles on the current user’s account.|
|LinkGameCenter||Add Apple’s GameCenter to the social profiles on the current user’s account.|
|LinkGoogle||Add Google to the social profiles on the current user’s account.|
|LinkSteam||Add Steam to the social profiles on the current user’s account.|
|ListChannelMessages||List a channel’s message history.|
|ListFriends||List all friends for the current user.|
|ListGroups||List groups based on given filters.|
|ListGroupUsers||List all users that are part of a group.|
|ListLeaderboardRecords||List leaderboard records.|
|ListMatches||Fetch a list of running matches.|
|ListNotifications||Fetch a list of notifications.|
|ListStorageObjects||List publicly readable storage objects in a given collection.|
|ListUserGroups||List groups the current user belongs to.|
|PromoteGroupUsers||Promote a set of users in a group to the next role up.|
|DemoteGroupUsers||Demote a set of users in a group to a lower role.|
|ReadStorageObjects||Get storage objects.|
|UnlinkCustom||Remove the custom ID from the social profiles on the current user’s account.|
|UnlinkDevice||Remove the device ID from the social profiles on the current user’s account.|
|UnlinkEmail||Remove the email+password from the social profiles on the current user’s account.|
|UnlinkFacebook||Remove Facebook from the social profiles on the current user’s account.|
|UnlinkGameCenter||Remove Apple’s GameCenter from the social profiles on the current user’s account.|
|UnlinkGoogle||Remove Google from the social profiles on the current user’s account.|
|UnlinkSteam||Remove Steam from the social profiles on the current user’s account.|
|UpdateAccount||Update fields in the current user’s account.|
|UpdateGroup||Update fields in a given group.|
|WriteLeaderboardRecord||Write a record to a leaderboard.|
|WriteStorageObjects||Write objects into the storage engine.|
Names are case-insensitive. For more information, see
For real-time before and after hooks, use the following message names:
|ChannelJoin||Join a realtime chat channel.|
|ChannelLeave||Leave a realtime chat channel.|
|ChannelMessageSend||Send a message to a realtime chat channel.|
|ChannelMessageUpdate||Update a message previously sent to a realtime chat channel.|
|ChannelMessageRemove||Remove a message previously sent to a realtime chat channel.|
|MatchCreate||A client to server request to create a realtime match.|
|MatchDataSend||A client to server request to send data to a realtime match.|
|MatchJoin||A client to server request to join a realtime match.|
|MatchLeave||A client to server request to leave a realtime match.|
|MatchmakerAdd||Submit a new matchmaking process request.|
|MatchmakerRemove||Cancel a matchmaking process using a ticket.|
|PartyCreate||A client to server request to create a party.|
|PartyJoin||A client to server request to join a party.|
|PartyLeave||A client to server request to leave a party.|
|PartyPromote||A client to server request to promote a party member.|
|PartyAccept||A client to server request to accept a party join request.|
|PartyRemove||A client to server request to remove a party member.|
|PartyClose||A client to server request to close a party.|
|PartyJoinRequestList||A client to server request to list all join requests for a particular party.|
|PartyMatchmakerAdd||Submit a new party matchmaking process request.|
|PartyMatchmakerRemove||Cancel a party matchmaking process using a ticket.|
|PartyDataSend||A client to server request to send data to a party.|
|StatusFollow||Start following some set of users to receive their status updates.|
|StatusUnfollow||Stop following some set of users to no longer receive their status updates.|
|StatusUpdate||Set the user’s own status.|
Names are case-insensitive. For more information, have a look at
Background jobs #
To avoid “dead work” - done when the user is not present - and the unnecessary server load, background jobs should be avoided in favor of an event driven route. In this approach, the client makes an RPC call when the user returns, and in that called function any updates required by your game logic and use case are performed.
Where a scheduled background job would needlessly perform these updates across the entire user base, regardless of a user’s inactivity, this approach ensures that work is only performed for users still active in the game.
Use of background jobs can cause further problems as any job would be limited to one Nakama instance, requiring either duplication across all instances or a non-homogenous workload across instances.