@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
apps/client/src/main.ts
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.
-
NetworkServerLibraryneeds the Bun runtime, whichnfuses to run servers. -
With pnpm, a bundled server can fail to start with
Cannot load native addon for node-datachannel. Add this topnpm-workspace.yaml:
Environment variables
Both libraries read their settings from the environment, validated atapp.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
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
- Client networking and Server networking: send and receive data and typed packets, identify clients.
- Peer-to-peer: let a player host the game.
- Packet channels: what each channel guarantees and how packets are framed.
- Client API and Server API: every method and type.