Supercharge Your Game’s Social Features with Nakama

Rate this content
Bookmark

Explore the impact of social features on game success and learn how to integrate them swiftly with Nakama OSS game server. This session will guide you through code examples, revealing how to enhance your game’s social capabilities. Discover a faster, simpler way to supercharge your game development journey and unleash your game’s social potential with Nakama!

17 min
28 Sep, 2023

Video Summary and Transcription

Social features in games increase player engagement, drive in-app purchases, and allow for community building. Nakama is a tool that enables the addition of multiple social features to games, such as authentication, friend management, and leaderboards. The implementation process involves installing the nakama.js package, creating a client object, and using custom authentication. Users can log out, manage friends, view user information, and interact with leaderboards. Additionally, Nakama allows for the implementation of player participation rewards through custom code.

Available in Español

1. Introduction to Social Features in Games

Short description:

Hi, I'm Tom Glenn, a software engineer with 15 years of experience. Heroic Labs is a team of 40 people, creators of the open-source game back-end Nakama. Social experiences in games, like adding friends and participating in leaderboards, are important because they increase player engagement and allow for community building. These features can also drive in-app purchases and monetization opportunities.

♪♪ Hi, I'm Tom, and welcome to this talk on how to supercharge your games' social features with Nakama. Before we begin, let me give you a brief background on who I am. I'm Tom Glenn, I'm a software engineer with roughly 15 years of experience across a wide variety of sectors, including web development, banking, 3D simulations, and more. I'm also an engineer and part of the developer relations team here at Heroic Labs, as well as a content creator and educator over on YouTube, and you can find me at CodeWithTom.

So who are Heroic Labs? Well, we're a team of roughly 40 people and creators of the open-source game back-end, Nakama. We power some of the largest multiplayer games across mobile and desktop, and our clients include the likes of Paradox Interactive, Lightheart Entertainment, Lion Studios, and more. Our other products include our live ops platform, Satori, as well as our game framework, Hero, and Heroic Cloud for our managed server hosting.

So what are social experiences? I have no doubt you will all have experienced these before, but social experiences in games can include things like being able to add friends, participate in leaderboards, chat to other players, join groups or guilds, complete achievements, and show them off on your public profile, take part in live events, and so on. There are so many different kinds of social experiences that you can encounter in games today. But why are these important? Well, multiplayer and cooperative experience have been shown to increase the amount of time that players spend in your game, and social competitions such as leaderboards keep your players coming back for more. They can also allow your players to form communities with shared interests and experiences, and this can lead to an increased player base as players are incentivized to invite friends, share achievements, and collaborate to complete goals. Social features, such as gifting or live events, can also drive in-app purchases and open the door for other monetization opportunities.

2. Adding Social Features with Nakama

Short description:

I will demonstrate how to add multiple social features to your game using Nakama. We'll cover authentication, adding and listing friends, viewing leaderboards, submitting scores, and rewarding player participation. To implement these functions, we'll install the nakama.js package, create a client object, and use the custom authentication method. The authenticate function returns a session object, allowing us to access different user account information. After implementing the restore session flow, users will be automatically logged in when they return to the application. Finally, we'll implement a log-out function to complete the authentication flow.

So rather than talk to you about the theory of adding social features to your game, what I want to do is give you a practical demonstration of how you can add multiple social features to your game using Nakama. We're going to quickly run through how to add authentication, adding and listing friends, viewing a global and a friend-specific leaderboard, submitting scores to that leaderboard, and then rewarding that player participation by giving the player some coins for participating in that leaderboard.

So let's jump over to the code. Okay, so you can see we've got our demo application running here. It's a simple React application with a login screen that if I try to log in right now, nothing's going to happen because we haven't implemented any of these functions here which the React application is expecting to call to perform various things such as authenticating, getting the account details, adding a list in friends, and so on. So what I'd like to do is quickly run through how easy it is to implement these functions using Nakama.

So before I start, what I have done here is I've ran npm install and I have installed the nakama.js package which you can find at heroic.labs.nakama-js. Once you've done that, we can then import the client and session object from the nakama.js package. We're then going to create a client object. Now, this client object expects to take a server key, the default one is default-key, the host address of the Nakama instance, in which case I'm currently running this using Docker on my local machine, and the port number for where the Nakama instance is running. We're then gonna implement the authenticate function. Now, Nakama supports various different mechanisms for authentication, these include device authentication, email and password, Apple, Google, Facebook, and custom authentication to name a few. We're gonna use custom authentication here just because it allows us to pass in a custom identifier as well as a username, and this true flag here also allows us to specify if the user account doesn't already exist, then we will go ahead and create it. Now, this authenticate custom function as well as all of the other authenticate functions will return a session object, which you can see we have up here. This session object allows us then to call into various other functions within Nakama to get different pieces of information for that user account. If we save this file now and come over to our login screen and try and log in again, you can see that we are now logged in. It says, hi, CodewithTom. We can't access anything such as friends or leaderboard right now as we haven't implemented those functions, but let's go ahead and do that now. I'll just quickly log out.

And before we go any further in to get an account or anything else, what I'd like to do is implement a restore session flow so that the next time the user comes back to the application, they don't have to re-log into their account. To do that, we're going to set, we're going to get rather two items from local storage. These are going to be session token and refresh token. Now, we're also going to have to set these items. So what we'll do is just after we authenticate, we will go to local storage and set the session token as our session.token value and the refresh token as the session.refresh token. We'll also implement a function here called restore session. And what we're going to do here is we're going to get the two values for session token and refresh token just to make sure we have the most up-to-date version. And if they have a value, then we're going to use the session.restore. Now this is a function that lives on the session class itself passing the session token and the refresh token and assign that value back to our session variable. We will save that and let's log in here code with Tom and you can see now if I refresh the page I'm automatically logged back in, which is great. Now, the last thing we need to do is implement a log-out function and that is our authentication flow complete.

3. Logging Out and Managing Friends

Short description:

To log out, we call the client.sessionLogOut function and remove the session object and tokens. To get the friends list, we use the listFriends function and filter out friends with a state of three. Adding friends is done by calling the addFriends function with the username. After logging in as CodewithTom, we can add a friend and see the request sent. No password is used in the custom authentication flow.

To do that, we are going to call the client.sessionLogOut function. This takes our session object as well as the token and refresh token. We're then going to nullify our session object and then just remove those tokens from the local storage. So let's just refresh that here and log back out and you can see we have now been logged out and if I refresh that page, we no longer log back in as code with Tom.

So let's just quickly log back in. The next thing we want to do is implement the getFriends list. Now, to do this all we need to do is call the listFriends function on our client object. We're then going to check to see if the result contained a value just to make sure that we have a value coming back from the server and we're going to filter it for any friends that have a state of three. We don't want any friends that have a state of three.

Now you can head over to the Nakama documentation and have a look at what the friend states are but these can include a mutual friend where you've both added each other. It includes a sent requests when you've sent a friend request to somebody else, a received request when you've received a request from someone and three, which is banned if either user has blocked each other. So we don't wanna include any users that have blocked each other here. If we find no friends, we're just gonna return null. Now if I save this and refresh, we're not gonna see anything because we haven't added any friends yet.

So how do we do that? Well, we can simply call the addFriends function, client.addFriends. We pass in our session object. This one here is the ID, user IDs for any users that we would like to add as a friend. So you can optionally add friends by ID or you can do it by username. In this case, our function is expecting to take a username, so we're just gonna add them by username. So let's save this, and then let's... Well, if we try and add a friend now, there are no other users in the system. So what we'll do is we'll quickly log back out and we'll add another user. So let's call this user, testUser. We'll log in, and you can see now that we can go and add a friend. So let's add CodeWithTom. And you can see that we have a one friend here, CodeWithTom, and we have sent that request. Let's log out and log in as CodewithTom. Now, you also notice here I'm not using a password. That's just because we're using that custom authentication flow. If you wanted to use a username or password, then you can use the email and password flow as well.

4. Adding Friends, User Information, and Leaderboards

Short description:

We can add friends, view friend statuses, and implement a getAccount function to display user information. Additionally, we can implement leaderboards, including listing leaderboard records and submitting scores.

You can see here we've received a request from testUser. Now, in order to mutually add that user back, all we need to do is just come in and add them as a friend as well. And that creates a mutual friendship. So that is how quick and easy it is to add a friend system to your game. We have a full add and send friend system here, as well as being able to list all of our friends and their current statuses, whether or not it was sent or received.

The next thing we're going to do is we're going to add in the getAccount function. Now, what this will do in this particular demo is it will display our current wallet. Now, I won't have any coins because this is a brand new account, but let's just implement that function quickly anyway by calling the client.getAccount function. This takes our session, and as part of this, we can just quickly take a look. The result here, we can get all of the information about that user. So we can say what their email address is, what their wallet details are, and we can also go in and get various things such as their avatar URL, and so on. Let's just delete that line there. And now, this will be implemented.

So the next thing we need to do is implement our leaderboards functionality. So the first thing I would like to do is implement the list leaderboard function for our global leaderboard. And what we're gonna do here is we're gonna say listLeaderboardRecords. We're gonna give it our session token, and we're gonna pass in the identifier for the leaderboard that we would like to get. In this case, we have a leaderboard set up on our Nakima server called Weekly underscore leaderboard. Now, we're gonna pass in null here for the owner IDs value, which means that we don't want to get leaderboard records for specific users. We just want them for everybody. And 100 is how many records do we want to receive from that leaderboard? So we're gonna say we want the top 100 records. We're then passing back the result.records object here. And if I refresh this and go to leaderboards, again, you're not gonna see anything here because nobody has submit a score yet.

So let's quickly add the submit score function. Down here, we're gonna call write leaderboard record. We're giving it our session. We're giving it that weekly leaderboard identifier again. And we're going to give the score value, which is gonna come from this input field. Now, obviously in this case, we're just submitting a score directly, but you would submit a score at the end of your gameplay mechanic. For example, when the round ends, you would then call this function with whatever score the player has achieved.

5. Implementing Social Features with Nakama

Short description:

So let's save this and refresh. If I come over to the leaderboard now and submit a score of 100, you'll see that CodeWithTom is now in rank one and has 100 points. We're calling our getFriends function, mapping all of our friends and getting their user IDs. We're then calling list leaderboard records to get their specific records. Let's save that and refresh the page. Now, you can see here that I can only see Code with Tom. Let's log out and go and submit a record for test user. If we go to the leaderboard we can see Code with Tom. If we go to the friends leaderboard, we can also see Code with Tom as Code with Tom is in our friends list. So let's submit a score of 500. And you can see now that we're now rank one and Code with Tom is rank two. That's how we can implement social features in our game using Nakama.

So let's save this and refresh. If I come over to the leaderboard now and submit a score of 100, you'll see that CodeWithTom is now in rank one and has 100 points. I come to the friends leaderboard, you'll see that there is nothing in here right now because we haven't implemented the get friends leaderboard function.

So let's quickly do that now. This one's gonna be a bit more involved and I'll run you through how it's done. So first of all, we're calling our getFriends function, which we implemented up here. If there aren't any friends, then we're just gonna return nothing. Otherwise, we're gonna go and map all of our friends and get all of their user ID's. We're then gonna add ourself to the user ID list just so that we can include ourselves in that ranking. We're then gonna call list leaderboard records, again, passing in the session and the weekly ID. And then we're gonna pass in the friend ID's where that owner ID's parameter is. And this is gonna mean that we go and get their specific records from the leaderboard. Again, we're gonna say 100 records, and then what we're gonna do is instead of returning result.records, we're gonna return result.ownerrecords. Let's save that and refresh the page. Come to leaderboard and go to friends. Now, you can see here that I can only see Code with Tom. That's because our friend test user has still not submitted a record. So let's log out and go and submit a record for test user. If we go to the leaderboard we can see Code with Tom. If we go to the friends leaderboard, we can also see Code with Tom as Code with Tom is in our friends list. So let's submit a score of 500. And you can see now that we're now rank one and Code with Tom is rank two. Perfect.

So that's how we can implement a bunch of social features in our game very quickly using Nakama. Everything you've seen so far has been done with client-side code. However, Nakama is extremely flexible and it does allow you to extend the game server itself using TypeScript. You can write your own custom code, your own functions, or interact with the Nakama lifecycle hooks to do various things such as provide daily logging rewards when the player first logs in for the day. Or you might want to add a profanity filter to chat messages just before they get sent. You may also want to add things such as guild creation requirements, thereby restricting players from creating guilds or groups until perhaps say they reach level 10 in your game. What I'd like to do now is show you a practical example of how you can extend Nakama by implementing a player participation reward for whenever the player submits a leaderboard score that's greater than or equal to 1,000.

6. Implementing Player Participation Reward

Short description:

To implement the player participation reward, we use an afterhook on the write leaderboard record lifecycle event. If the score is greater than or equal to 1,000, we call the nk.walletUpdate function to give the user 1,000 coins. By running the Nakama instance and submitting a score of 1,000, we can see the coins increase. Adding custom functionality to Nakama is quick and easy with TypeScript code.

When that happens, we're going to give them 1,000 coins in their virtual wallet. Let's dive back over to the code. So in order to implement our player participation reward, we're actually going to use a afterhook. Now, this is going to be a hook on our write leaderboard record lifecycle event within Nakama. To do this, we're going to use our initializer up here, and we're going to say initializer.registerAfter writeLeaderboardRecord, and then we're going to give it the name of a function. Now, we're going to define this function below. And all this function is going to do is it's going to use this data parameter here, which is a leaderboard record, and we're going to say data.score, and we're going to say if it's greater than or equal to 1,000, then we're going to call the nk.walletUpdate function. Now, this function expects to take a user ID and then a change set for how we want to change the user's wallet. So we're going to pass in the data.ownerId for the owner of the leaderboard record being submit, and then we're going to call the changeSet function with a value of coins for the key and 1,000 for the property, and this is going to give them 1,000 coins. Let's save this, and then what I'm going to quickly do is rerun the Nakama instance via Docker, and then if I refresh this screen here, and let's log out, and let's log in as Code with Tom, let's come over to our leaderboard, and now I'm going to submit a value of 1,000. Now, hopefully we should see that our coins increase, and they do. So our coins there have increased by 1,000, and that is how quick and easy it is to add custom functionality to your Nakama server by writing TypeScript code.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Building Fun Experiments with WebXR & Babylon.js
Top Content
During this session, we’ll see a couple of demos of what you can do using WebXR, with Babylon.js. From VR audio experiments, to casual gaming in VR on an arcade machine up to more serious usage to create new ways of collaboration using either AR or VR, you should have a pretty good understanding of what you can do today.
Check the article as well to see the full content including code samples: article. 
React Summit 2023React Summit 2023
32 min
How Not to Build a Video Game
In this talk we'll delve into the art of creating something meaningful and fulfilling. Through the lens of my own journey of rediscovering my passion for coding and building a video game from the ground up with JavaScript and React, we will explore the trade-offs between easy solutions and fast performance. You will gain valuable insights into rapid prototyping, test infrastructure, and a range of CSS tricks that can be applied to both game development and your day-to-day work.

Workshops on related topic

JSNation 2023JSNation 2023
116 min
Make a Game With PlayCanvas in 2 Hours
Featured WorkshopFree
In this workshop, we’ll build a game using the PlayCanvas WebGL engine from start to finish. From development to publishing, we’ll cover the most crucial features such as scripting, UI creation and much more.
Table of the content:- Introduction- Intro to PlayCanvas- What we will be building- Adding a character model and animation- Making the character move with scripts- 'Fake' running- Adding obstacles- Detecting collisions- Adding a score counter- Game over and restarting- Wrap up!- Questions
Workshop levelFamiliarity with game engines and game development aspects is recommended, but not required.
JS GameDev Summit 2022JS GameDev Summit 2022
121 min
PlayCanvas End-to-End : the quick version
Top Content
WorkshopFree
In this workshop, we’ll build a complete game using the PlayCanvas engine while learning the best practices for project management. From development to publishing, we’ll cover the most crucial features such as asset management, scripting, audio, debugging, and much more.
JS GameDev Summit 2022JS GameDev Summit 2022
86 min
Introduction to WebXR with Babylon.js
Workshop
In this workshop, we'll introduce you to the core concepts of building Mixed Reality experiences with WebXR and Balon.js.
You'll learn the following:- How to add 3D mesh objects and buttons to a scene- How to use procedural textures- How to add actions to objects- How to take advantage of the default Cross Reality (XR) experience- How to add physics to a scene
For the first project in this workshop, you'll create an interactive Mixed Reality experience that'll display basketball player stats to fans and coaches. For the second project in this workshop, you'll create a voice activated WebXR app using Balon.js and Azure Speech-to-Text. You'll then deploy the web app using Static Website Hosting provided Azure Blob Storage.