Skip to content

NATS Driver

The NATS Driver is a signaling driver that utilizes the NATS messaging system to enable communication between peers across different browsers and devices. This driver is ideal for scenarios where you want to establish peer-to-peer connections between multiple clients without the need for a custom signaling server. You can use the public NATS server at demo.nats.io for testing purposes, but it is recommended to set up your own NATS server for production applications to ensure better performance and security.

It is recommended to enable built-in namespace hashing and encryption for signaling messages when using the NATS Driver to ensure that sensitive information remains protected during transmission. This can be done by setting the appropriate options when creating a Peer instance.

Usage

To use the NATS Driver, simply import it from the Peerix library and create an instance:

import { NatsDriver } from 'peerix';
import { wsconnect } from '@nats-io/nats-core';

// connect to a NATS server (e.g. the public demo server) 
const nc = await wsconnect({ servers: ['wss://demo.nats.io:8443'] });

// create the NATS driver instance
const driver = new NatsDriver({
  // the NATS connection instance
  nc,
  // optional prefix for NATS subjects
  prefix: 'peerix',
});

You should install the @nats-io/nats-core package to use the NATS Driver, as it provides a WebSocket client for connecting to NATS servers from the browser. You can install it using your preferred package manager:

npm install @nats-io/nats-core

In this example, we create a new instance of the NATS Driver and specify the URL of the NATS server ('wss://demo.nats.io:8443'). You can also provide additional options as needed. All peers that connect to the same NATS server will be able to discover each other and exchange messages.

Benefits of Using the NATS Driver

  • Scalability: NATS is designed for high performance and can handle a large number of connections and messages, making it suitable for applications with many peers.
  • Simplicity: Using NATS as a signaling mechanism abstracts away the complexities of managing a custom signaling server, allowing you to focus on building your application.
  • Cross-platform: NATS can be used across different platforms and environments, making it a versatile choice for signaling in peer-to-peer applications.
  • Security: NATS supports secure connections and authentication, allowing you to protect your signaling messages and ensure that only authorized peers can connect.
  • Open-source: NATS is an open-source project with an active community, providing ongoing support and improvements.
  • Integration: NATS can be easily integrated with other systems and services, allowing you to build complex applications that leverage the full potential of the NATS ecosystem.