Skip to main content
@nanoforge-dev/network connects game clients to a game server. It has one library per side: Shared definitions, such as Channel and definePacket, come from @nanoforge-dev/network. Both libraries are reached through ctx.network. Each packet goes on one of four channels: reliable or unreliable, ordered or unordered. Reliable channels use a TCP WebSocket; unreliable ones use WebRTC data channels, for low-latency updates such as positions. A game can also run without a dedicated server: one player’s browser hosts the game. See Peer-to-peer.

Set up a client and a server

Create the project with a server: nf new and answer yes to the server prompt. It generates apps/client and apps/server, each with its network library registered. Put the packet definitions both sides use in a shared file:
shared/protocol.ts
Register the client library:
apps/client/src/main.ts
And the server library, with the server ECS:
apps/server/src/main.ts
  • The client connects during app.init, which rejects when the server can’t be reached within 10 seconds.
  • Each tick, the network library runs before the ECS: the packets received are ready for your systems.
  • NetworkServerLibrary needs the Bun runtime, which nf uses to run servers.
  • With pnpm, a bundled server can fail to start with Cannot load native addon for node-datachannel. Add this to pnpm-workspace.yaml:
Then send and receive packets: see Client networking and Server networking. The pong-network example is a complete game.

Environment variables

Both libraries read their settings from the environment, validated at app.init. Set them in the project’s .env file: prefix a variable with NANOFORGE_CLIENT_ for the client, NANOFORGE_SERVER_ for the server, or NANOFORGE_ for both. See Environment for where secrets may go.
.env
Client variables: Server variables: Both sides: The client fails at start-up when it has neither port, and the server when it has neither listening port. A channel whose port is not set throws when used, except on a peer-to-peer host, where every channel works.

Pages in this section