Top Related Projects
⚔ Multiplayer Framework for Node.js
Developer-first error tracking and performance monitoring
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
Firebase Javascript SDK
Quick Overview
Nakama is an open-source server designed for realtime multiplayer games and apps. It provides a scalable, flexible backend with features like user accounts, social networking, matchmaking, and realtime multiplayer support. Nakama is built with Go and can be deployed on-premises or in the cloud.
Pros
- Comprehensive feature set for game development, including authentication, leaderboards, and chat systems
- Supports multiple programming languages and platforms (Unity, Unreal, JavaScript, etc.)
- Highly scalable and performant, suitable for large-scale multiplayer games
- Self-hosted solution, giving developers full control over their infrastructure and data
Cons
- Steeper learning curve compared to some managed backend services
- Requires more setup and maintenance than fully managed alternatives
- Documentation can be overwhelming for beginners due to the extensive feature set
- Limited community support compared to some more popular game development backends
Code Examples
- Connecting to a Nakama server:
const client = new Client("defaultkey", "127.0.0.1", 7350);
const session = await client.authenticateEmail("email@example.com", "password");
console.log("Connected to Nakama server:", session.token);
- Creating and joining a multiplayer match:
const match = await client.createMatch();
console.log("Created match:", match.matchId);
const joinedMatch = await client.joinMatch(match.matchId);
console.log("Joined match:", joinedMatch.matchId);
- Sending and receiving realtime messages:
const socket = client.createSocket();
await socket.connect(session);
socket.onmatchdata = (matchData) => {
console.log("Received match data:", matchData.data);
};
await socket.sendMatchState(matchId, 1, { position: { x: 10, y: 20 } });
Getting Started
-
Install Nakama server (using Docker):
docker run --name nakama-server -d -p 7350:7350 -p 7351:7351 heroiclabs/nakama:3.15.0
-
Install the Nakama client library for your platform (e.g., for JavaScript):
npm install @heroiclabs/nakama-js
-
Initialize the client and authenticate:
import { Client } from "@heroiclabs/nakama-js"; const client = new Client("defaultkey", "127.0.0.1", 7350); const session = await client.authenticateDevice("device_id"); console.log("Connected to Nakama server:", session.token);
-
Start using Nakama features in your game or app!
Competitor Comparisons
⚔ Multiplayer Framework for Node.js
Pros of Colyseus
- Lightweight and easy to set up, with a focus on real-time multiplayer game development
- Built-in room and state synchronization mechanisms
- Active community and regular updates
Cons of Colyseus
- Limited built-in features compared to Nakama's comprehensive backend solution
- Less scalable for large-scale projects without additional infrastructure
- Primarily focused on JavaScript/TypeScript ecosystems
Code Comparison
Colyseus (TypeScript):
import { Room, Client } from "colyseus";
class GameRoom extends Room {
onCreate(options: any) {
this.setState({ players: {} });
}
onJoin(client: Client, options: any) {
this.state.players[client.sessionId] = { x: 0, y: 0 };
}
}
Nakama (Go):
func (m *Match) MatchInit(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, params map[string]interface{}) (interface{}, int, string) {
state := &MatchState{
Players: make(map[string]*Player),
}
return state, 0, ""
}
func (m *Match) MatchJoinAttempt(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, dispatcher runtime.MatchDispatcher, tick int64, state interface{}, presence runtime.Presence, metadata map[string]string) (interface{}, bool, string) {
mState := state.(*MatchState)
mState.Players[presence.GetUserId()] = &Player{X: 0, Y: 0}
return mState, true, ""
}
Developer-first error tracking and performance monitoring
Pros of Sentry
- Comprehensive error tracking and monitoring across multiple platforms and languages
- Extensive integrations with popular frameworks and services
- Large and active community with frequent updates and contributions
Cons of Sentry
- More complex setup and configuration compared to Nakama
- Higher resource requirements for self-hosted installations
- Steeper learning curve for advanced features and customizations
Code Comparison
Sentry (Python):
import sentry_sdk
sentry_sdk.init(
dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
traces_sample_rate=1.0
)
try:
division_by_zero = 1 / 0
except Exception as e:
sentry_sdk.capture_exception(e)
Nakama (Go):
import "github.com/heroiclabs/nakama-common/runtime"
func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, initializer runtime.Initializer) error {
if err := initializer.RegisterRpc("my_rpc", MyRpcFunction); err != nil {
return err
}
return nil
}
The code snippets demonstrate the basic setup and error handling in Sentry versus registering an RPC function in Nakama. Sentry focuses on error tracking, while Nakama is geared towards game server functionality.
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
Pros of Supabase
- More comprehensive platform with built-in authentication, storage, and real-time subscriptions
- Easier setup and management through a user-friendly dashboard
- Stronger focus on web and mobile app development
Cons of Supabase
- Less specialized for game development compared to Nakama
- May have higher latency for real-time multiplayer gaming scenarios
- Limited support for custom server-side logic compared to Nakama's runtime modules
Code Comparison
Supabase (JavaScript):
const { data, error } = await supabase
.from('users')
.select('*')
.eq('id', userId)
Nakama (Go):
users, err := nk.UsersGetId(ctx, []string{userId})
if err != nil {
// Handle error
}
Both Supabase and Nakama are open-source backend platforms, but they cater to different primary use cases. Supabase is a more general-purpose backend-as-a-service solution, offering a PostgreSQL database with additional features like authentication and real-time subscriptions. It's particularly well-suited for web and mobile app development.
Nakama, on the other hand, is specifically designed for game development, providing features like matchmaking, leaderboards, and real-time multiplayer support. It offers lower latency for gaming scenarios and more flexibility in terms of custom server-side logic through its runtime modules.
The choice between the two depends on the specific needs of your project, with Supabase being more versatile for general app development and Nakama excelling in game-specific scenarios.
Firebase Javascript SDK
Pros of Firebase JS SDK
- Extensive documentation and large community support
- Seamless integration with other Google Cloud services
- Real-time database and cloud functions out of the box
Cons of Firebase JS SDK
- Vendor lock-in to Google's ecosystem
- Limited customization options for advanced use cases
- Potential for higher costs at scale
Code Comparison
Firebase JS SDK:
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
set(ref(db, 'users/' + userId), { username: name, email: email });
Nakama:
import { Client } from '@heroiclabs/nakama-js';
const client = new Client("defaultkey", "127.0.0.1", 7350);
const session = await client.authenticateCustom('unique_id');
const account = await client.getAccount(session);
Both Firebase JS SDK and Nakama offer real-time capabilities and backend-as-a-service features. Firebase provides a more comprehensive ecosystem with additional services, while Nakama focuses on game development with features like matchmaking and leaderboards. Firebase is easier to set up and use for beginners, but Nakama offers more flexibility and control over the backend infrastructure. The choice between the two depends on specific project requirements and the level of customization needed.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Distributed server for social and realtime games and apps.
Features
- Users - Register/login new users via social networks, email, or device ID.
- Storage - Store user records, settings, and other objects in collections.
- Social - Users can connect with friends, and join groups. Builtin social graph to see how users can be connected.
- Chat - 1-on-1, group, and global chat between users. Persist messages for chat history.
- Multiplayer - Realtime, or turn-based active and passive multiplayer.
- Leaderboards - Dynamic, seasonal, get top members, or members around a user. Have as many as you need.
- Tournaments - Invite players to compete together over prizes. Link many together to create leagues.
- Parties - Add team play to a game. Users can form a party and communicate with party members.
- Purchase Validation - Validate in-app purchases and subscriptions.
- In-App Notifications - Send messages and notifications to connected client sockets.
- Runtime code - Extend the server with custom logic written in Lua, TypeScript/JavaScript, or native Go code.
- Matchmaker, dashboard, metrics, and more.
Build scalable games and apps with a production ready server used by ambitious game studios and app developers all around the world. Have a look at the documentation and join the developer community for more info.
Getting Started
The server is simple to setup and run for local development and can be deployed to any cloud provider. See the deployment notes for recommendations on how to deploy the project for production. Nakama server requires CockroachDB or another Postgres wire-compatible server as it's database.
Docker
The fastest way to run the server and the database is with Docker. Setup Docker and start the daemon.
-
Set up a docker-compose file and place it in a folder for your project.
-
Run
docker-compose -f ./docker-compose.yml up
to download container images and run the servers.
For more detailed instructions have a look at our Docker quickstart guide.
Nakama Docker images are maintained on Docker Hub and prerelease images are occasionally published for cutting edge features of the server.
Binaries
You can run the servers with native binaries for your platform.
-
Download the server from our releases page and the database.
-
Follow the database instructions to start it.
-
Run a migration which will setup or upgrade the database schema:
nakama migrate up --database.address "root@127.0.0.1:26257"
-
Start Nakama and connect to the database:
nakama --database.address "root@127.0.0.1:26257"
When connected you'll see server output which describes all settings the server uses for configuration.
{"level":"info","ts":"2018-04-29T10:14:41.249+0100","msg":"Node","name":"nakama","version":"2.0.0+7e18b09","runtime":"go1.10.1","cpu":4}
{"level":"info","ts":"2018-04-29T10:14:41.249+0100","msg":"Database connections","dsns":["root@127.0.0.1:26257"]}
...
Usage
Nakama supports a variety of protocols optimized for various gameplay or app use cases. For request/response it can use GRPC or the HTTP1.1+JSON fallback (REST). For realtime communication you can use WebSockets or rUDP.
For example with the REST API to authenticate a user account with a device identifier.
curl "127.0.0.1:7350/v2/account/authenticate/device?create=true" \
--user "defaultkey:" \
--data '{"id": "someuniqueidentifier"}'
Response:
{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjQ5OTU2NDksInVpZCI6Ijk5Y2Q1YzUyLWE5ODgtNGI2NC04YThhLTVmMTM5YTg4MTgxMiIsInVzbiI6InhBb1RxTUVSdFgifQ.-3_rXNYx3Q4jKuS7RkxeMWBzMNAm0vl93QxzRI8p_IY"
}
There's a number of official client libraries available on GitHub with documentation. The current platform/language support includes: .NET (in C#), Unity engine, JavaScript, Java (with Android), Unreal engine, Godot, Defold, and Swift (with iOS). If you'd like to contribute a client or request one let us know.
Nakama Console
The server provides a web UI which teams can use to inspect various data stored through the server APIs, view lightweight service metrics, manage player data, update storage objects, restrict access to production with permission profiles, and gain visibility into realtime features like active multiplayer matches. There is no separate installation required as it is embedded as part of the single server binary.
You can navigate to it on your browser on http://127.0.0.1:7351.
Deployment
Nakama can be deployed to any cloud provider such as Google Cloud, Azure, AWS, Digital Ocean, Heroku, or your own private cloud. You should setup and provision separate nodes for Nakama and CockroachDB.
The recommended minimum production infrastructure for CockroachDB is outlined in these docs and Nakama can be run on instance types as small as "g1-small" on Google Cloud although we recommend a minimum of "n1-standard-1" in production. The specific hardware requirements will depend on what features of the server are used. Reach out to us for help and advice on what servers to run.
Heroic Cloud
You can support development, new features, and maintainance of the server by using the Heroic Labs' Heroic Cloud for deployment. This service handles the uptime, replication, backups, logs, data upgrades, and all other tasks involved with production server environments.
Have a look at our Heroic Cloud service for more details.
Contribute
The development roadmap is managed as GitHub issues and pull requests are welcome. If you're interested to add a feature which is not mentioned on the issue tracker please open one to create a discussion or drop in and discuss it in the community forum.
Simple Builds
All dependencies required for a build are vendored as part of the Go project. We recommend a modern release of the Go toolchain and do not store the codebase in the old GOPATH.
-
Download the source tree.
git clone "https://github.com/heroiclabs/nakama" nakama cd nakama
-
Build the project from source.
go build -trimpath -mod=vendor ./nakama --version
Full Source Builds
The codebase uses Protocol Buffers, GRPC, GRPC-Gateway, and the OpenAPI spec as part of the project. These dependencies are generated as sources and committed to the repository to simplify builds for contributors.
To build the codebase and generate all sources follow these steps.
-
Install the toolchain.
go install \ "google.golang.org/protobuf/cmd/protoc-gen-go" \ "google.golang.org/grpc/cmd/protoc-gen-go-grpc" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2"
-
If you've made changes to the embedded Console.
cd console/ui ng serve
-
Re-generate the protocol buffers, gateway code and console UI.
env PATH="$HOME/go/bin:$PATH" go generate -x ./...
-
Build the codebase.
go build -trimpath -mod=vendor
Testing
In order to run all the unit and integration tests run:
docker-compose -f ./docker-compose-tests.yml up --build --abort-on-container-exit; docker-compose -f ./docker-compose-tests.yml down -v
This will create an isolated environment with Nakama and database instances, run all the tests, and drop the environment afterwards.
License
This project is licensed under the Apache-2 License.
Top Related Projects
⚔ Multiplayer Framework for Node.js
Developer-first error tracking and performance monitoring
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
Firebase Javascript SDK
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot