Skip to content

Quickstart

Getting started with Swarm is quick and easy. Just follow the steps below and you'll be up and running in no time.

Installation

You can install @nhtio/swarm directly from your preferred package manager

sh
npm i @nhtio/swarm
sh
pnpm add @nhtio/swarm
sh
yarn add @nhtio/swarm

Setting the Pre-Shared Key

In order to ensure that messages being passed between nodes in the swarm are readable only by other nodes in the swarm, you must either use the setPSK method which can be imported from the main package, or you must pass the PSK as the first argument to the first call which you make to Swarm.instance.

typescript
import { Swarm, setPSK } from '@nhtio/swarm'

setPSK('someverylongvaluewhichisatleast16characterslong')
const instance = Swarm.instance()

// or

const instance = Swarm.instance('someverylongvaluewhichisatleast16characterslong')

Under the hood

In order to faciliate serialization and to ensure that messages being sent between nodes in the swarm are only readable by other nodes which have been appropriately configured, @nhtio/web-encryption is used as the serialization / deserialization mechanism. This both adds additional flexibility in the serialization as @nhtio/web-encryption uses @nhtio/web-serialization to handle the serialization of data, but also adds a mechanism to ensure that only contexts which have been configured correctly can access messages from the swarm.

Accessing the Swarm

Import the Swarm class from @nhtio/swarm

typescript
import { Swarm } from '@nhtio/swarm'

Initialize the instance by calling the Swarm.instance static method

typescript
const instance = Swarm.instance()

Type Safety

Swarm is a strongly-typed library. Before using it, you should create an Event Map which extends TypedEventMap.

typescript
import { Swarm } from '@nhtio/swarm'
import type { TypedEventMap } from '@nhtio/swarm/types'

type Bar = string

interface MyTypedEventMap extends TypedEventMap {
    foo: [Bar]
    baz: []
}

const instance = Swarm.instance<MyTypedEventMap>()