Skip to main content

NanoForge


npm versionnpm downloadsTests statusLast commitContributors

About

@nanoforge-dev/network is NanoForge’s built-in networking library. It ships two subpath entry points — @nanoforge-dev/network/client and @nanoforge-dev/network/server — each sending packets on four channels: Channel.ReliableOrdered and Channel.ReliableUnordered over TCP (WebSocket), Channel.UnreliableOrdered and Channel.UnreliableUnordered over UDP (WebRTC data channels). The root entry, @nanoforge-dev/network, exposes the types shared by both, such as NetworkConfig. Splitting client and server into separate entry points keeps the server’s runtime-only dependencies (Bun.serve, node-datachannel) out of a client’s bundle graph entirely. The same two entry points also run a game without a game server, hosted by one of the players (see Peer-to-peer).
The server entry point requires the Bun runtime. @nanoforge-dev/network/server is built on Bun’s native WebSocket server (Bun.serve) and does not run on Node.js. The client entry point is runtime-agnostic and targets the browser.

Installation

Node.js 26 or newer is required to build. The server entry point requires Bun 1.2 or newer at runtime.

Warning

Configuration is read from the environment via @nanoforge-dev/env. Put the relevant variables in your .env file (or InitContext.env):
Either the TCP port or the UDP port (or both) must be set on each side. The TCP port enables the reliable channels, the UDP port the unreliable ones.

Channels

Every method takes an optional { channel }. Sending defaults to Channel.ReliableOrdered, or to the definition’s channel for typed packets; reading covers every configured channel. One WebSocket per client carries both reliable channels: each binary frame starts with a one-byte channel tag. Each unreliable channel is its own data channel (ordered: false, maxRetransmits: 0); UnreliableOrdered packets are prefixed with a uint32 sequence number so the receiver drops any packet older than the last one it delivered. One message is one packet on every channel, so payloads may contain any bytes. Over TCP, ReliableUnordered is delivered in order in practice.

Payloads

The send methods take bytes, a string or any JSON value, and every received packet is a NetworkData you read in the format you need. Their payload carries no format tag: read a packet the way it was sent. Every packet starts with the name of its typed packet type, empty for these ones. NetworkData methods are synchronous and return a new value on every call. json() throws a SyntaxError when the payload is not JSON, and sending a value JSON.stringify cannot encode (undefined, a function) throws a TypeError.

Running the server behind a NAT

The UDP transport is a WebRTC data channel, so clients connect to the address the server puts in its ICE candidates. When the server sits behind a NAT — a Kubernetes pod, a container, a home router — the address it sees on its own interfaces is not the one clients can reach, and by default each peer also gets a random UDP port that no firewall rule or port forward can target. Three optional variables fix that. ICE_SERVERS applies to both sides; ICE_PORT and ADVERTISE_IP are server-only, since a browser can neither pin its UDP port nor rewrite its own candidates. With the nf CLI, a variable prefixed only with NANOFORGE_ (no CLIENT_/SERVER_) reaches both, so one line configures the ICE servers everywhere: NANOFORGE_ICE_SERVERS=stun:stun.example.com:3478.
  • ICE_SERVERS — STUN and TURN servers, as a comma-separated list of stun:/turn: URLs. Read by both the client and the server, since each builds its own peer connection. A STUN entry lets a peer behind a NAT discover its own public address; a TURN entry relays traffic when no direct path exists, typically for a client on a network that blocks UDP. TURN credentials cannot be embedded in the URL, so authenticated TURN uses the JSON form instead: ICE_SERVERS='[{"urls":"turn:turn.example.com:3478","username":"u","credential":"p"}]'.
  • ICE_PORT — pins the WebRTC transport to one fixed UDP port and enables ICE UDP multiplexing, so every client shares it. Forward or allow this single port.
  • ADVERTISE_IP — public address written into typ host ICE candidates in place of the local one. Addresses discovered through STUN are already public and are left untouched, so ICE_SERVERS and ADVERTISE_IP can be used together or apart.
On Kubernetes, pair ICE_PORT with a hostPort so the media path bypasses kube-proxy — a Service load-balances UDP across replicas, but a peer connection lives in exactly one pod — and take ADVERTISE_IP from the node:
Signalling needs no session affinity: the WebSocket is a single long-lived connection, so the pod that accepts it is the pod that owns the peer connection.

Bundling the server with pnpm

The UDP transport depends on node-datachannel, which loads its native addon at runtime with a bare require("@node-datachannel/<platform>"). A bundler inlines that call into your server bundle, where pnpm’s nested node_modules layout puts the platform package out of reach, and startup fails with Cannot load native addon for node-datachannel. Hoist the platform packages in pnpm-workspace.yaml:

Example usage

The client connects during __init and its channels are open before the game starts: __init rejects when a transport fails or the channels are not open within 10 seconds. The server starts listening during __init.

Typed packets

Declare each packet type once, in a file both apps import, then listen for it, read it from a system, or send it, with the payload type checked:
on returns a function that removes the listener. Typed packets never appear in getReceivedPackets, and a type nobody listens to or reads is dropped with a warning. Use definePacket’s validate option to check payloads on the server.

Client identification

Each client gets a ClientId (a random UUID string) shared by its TCP and UDP connections: the first transport receives the id and a session token in a welcome message, and the client presents the token when opening the other one. Use ctx.network.clients to follow sessions and ctx.network.getClientInfo to read what the server knows about a client (address, port, user agent, origin, query parameters):
On the client, ctx.network.clientId holds the id once the server has welcomed the client. A page reload starts a new session with a new id. Using a channel whose port wasn’t configured on that side throws.

Peer-to-peer

Set network: "p2p" in the workspace nanoforge.config.ts and the same client and server apps run without a game server: the first player to open the game hosts it, running the server app in their own tab, and the others join that tab over WebRTC, on the same four channels and typed packets. No game code changes.
  • nf build also builds the server app for the browser, into the client’s output. nf start sets NETWORK_MODE=p2p for both apps.
  • The Bun server process only pairs players (WebRTC signaling), on LISTENING_TCP_PORT. Players reach it with the usual SERVER_ADDRESS and SERVER_TCP_PORT, so the env stays the same as with a dedicated server.
  • A page opened without ?room= hosts a game; ?room=CODE joins one. The host logs its invite link, and the game can show it:
The game ends when the host leaves: each player’s isConnected() turns false. Keep packets at or below 64 KiB and add a TURN server to ICE_SERVERS for players behind strict NATs. The host’s server keeps its pace when its tab is hidden. See the peer-to-peer docs.

Contributing

Before creating an issue, please ensure that it hasn’t already been reported/suggested, and double-check the documentation.
See the contribution guide if you’d like to submit a PR.

Help

If you don’t understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don’t hesitate to ask questions in discussions.

Modules