PeerJS

repository·master·Indexed 12 days ago

https://github.com/peers/peerjs

A library providing a high-level API for peer-to-peer communication using WebRTC, supporting both data channels and media streams. Version 1.5.5 includes the Peer class for signaling, DataConnection for transmitting data, and MediaConnection for handling audio/video streams. It features experimental MsgPack serialization via MsgPackPeer and comprehensive configuration options for PeerServers and RTCConfiguration.

Tokens
5.2K
Snippets
20
Records
25
Agent score
46%

What's inside PeerJS

  1. Make and answer media calls

    master

    PeerJS supports media streams (audio/video) via WebRTC.

    To make a call, use peer.call(id, stream). You must provide a local media stream (e.g., from navigator.mediaDevices.getUserMedia). Listen for the stream event on the returned call object to receive the remote stream.

    To answer a call, listen for the call event on your Peer instance. Once a call is received, use call.answer(stream) to respond with your own local media stream. You can also listen for the stream event on the call object to receive the caller's stream.

    // --- Making a call ---
    navigator.mediaDevices.getUserMedia(
    	{ video: true, audio: true },
    	(stream) => {
    		const call = peer.call("another-peers-id", stream);
    		call.on("stream", (remoteStream) => {
    			// Use remoteStream in a <video> element
    		});
    	},
    	(err) => console.error(err)
    );
    
    // --- Answering a call ---
    peer.on("call", (call) => {
    	navigator.mediaDevices.getUserMedia(
    		{ video: true, audio: true },
    		(stream) => {
    			call.answer(stream);
    			call.on("stream", (remoteStream) => {
    				// Use remoteStream in a <video> element
    			});
    		},
    		(err) => console.error(err)
    	);
    });
  2. Establish and receive data connections

    master

    PeerJS allows for peer-to-peer data exchange via data channels.

    To connect to another peer, use peer.connect(id). You should listen for the open event before attempting to send data.

    To receive a connection, listen for the connection event on your Peer instance. Once a connection object is received, you can listen for the data event to receive messages and the open event to respond to the sender.

    // --- Connecting to a peer ---
    const conn = peer.connect("another-peers-id");
    conn.on("open", () => {
    	conn.send("hi!");
    });
    
    // --- Receiving a connection ---
    peer.on("connection", (conn) => {
    	conn.on("data", (data) => {
    		// data is the received message
    		console.log(data);
    	});
    	conn.on("open", () => {
    		conn.send("hello!");
    	});
    });
  3. Troubleshoot Webpack dependency warning

    master
    If you see the message Critical dependency: the request of a dependency is an expression in your browser console while using Webpack, it is a known non-critical issue related to Parcel. It does not affect the functionality of PeerJS.
  4. Initialize a Peer instance

    master

    Import the Peer class and instantiate it. You can provide a specific ID for your peer or omit it to let the server assign a random one.

    import { Peer } from "peerjs";
    
    const peer = new Peer("pick-an-id");
    // Or omit the ID for a random one: const peer = new Peer();
  5. Configure PeerOptions

    master

    When initializing a Peer, you can pass a PeerOptions object to customize the connection to the signaling server.

    OptionTypeDefaultDescription
    debugLogLevel0Log level: 1 (Errors), 2 (Warnings), 3 (All logs).
    hoststring'0.peerjs.com'Server host. Use '/' for relative hostname.
    portnumber443Server port.
    pathstring'/'The path where your PeerServer is running.
    tokenstring(random)Token for the PeerServer.
    configanyutil.defaultConfigConfiguration hash passed to RTCPeerConnection (e.g., ICE/TURN servers).
    secureboolean(auto)Set to true if using TLS. Always use TLS if possible.
    pingIntervalnumber-Interval for pings.
    logFunctionfunction-Custom function to handle logs: (logLevel: LogLevel, ...rest: any[]) => void.
    serializersSerializerMapping{}Custom mapping for data connection serialization.
  6. Configure PeerJS connection options

    master

    When initializing a Peer instance, you can provide a PeerJSOption object to configure how the Peer connects to the PeerServer and how WebRTC is configured.

    Key options include:

    • key: The PeerServer key.
    • host: The PeerServer host.
    • port: The PeerServer port.
    • path: The PeerServer path.
    • secure: Whether to use a secure connection (HTTPS/WSS).
    • token: An authentication token for the PeerServer.
    • config: An RTCConfiguration object to pass directly to the browser's WebRTC implementation.
    • debug: A number to set the debug level.
    • referrerPolicy: The referrer policy to use.
    // Example PeerJSOption usage
    const peer = new Peer('my-id', {
      host: '0.0.0.0',
      port: 9000,
      path: '/peerjs',
      secure: false
    });
  7. Configure MediaCall options

    master

    When initiating a media call (via peer.call()), you can pass a CallOption object to customize the call.

    Key options include:

    • metadata: Any serializable data passed by the initiator. This is accessible via MediaConnection.metadata.
    • sdpTransform: A function that runs before the SDP answer is created, allowing you to modify the SDP answer message.
    // Example CallOption usage
    const call = peer.call('target-id', stream, {
      metadata: { callType: 'video' },
      sdpTransform: (sdp) => {
        // Modify SDP answer here
        return sdp;
      }
    });
  8. Configure DataConnection options

    master

    When creating a data connection (via peer.connect()), you can pass a PeerConnectOption object to customize the connection behavior.

    Key options include:

    • label: A unique identifier for the connection. If not provided, one is generated randomly. This is accessible via DataConnection.label.
    • metadata: Any serializable data passed by the initiator. This is accessible via DataConnection.metadata.
    • serialization: The serialization format to use.
    • reliable: A boolean determining if the connection should be reliable (TCP-like) or unreliable (UDP-like).
    // Example PeerConnectOption usage
    const conn = peer.connect('target-id', {
      label: 'chat-connection',
      metadata: { room: 'lobby', user: 'alice' },
      reliable: true
    });
  9. Browser support and requirements

    master

    PeerJS is tested against the following browsers:

    • Firefox: 80+
    • Chrome: 83+
    • Edge: 83+
    • Safari: 15+

    Note: Firefox 102+ is required if you want to use CBOR / MessagePack support.

  10. Use MsgPackPeer for MsgPack serialization

    master

    The MsgPackPeer class is an experimental extension of the standard Peer class that uses MsgPack for data serialization instead of the default JSON. This can be more efficient for certain types of data transfers. It inherits all methods and properties from the standard Peer class.

    import { MsgPackPeer } from './lib/msgPackPeer'; // Adjust path as necessary
    
    const peer = new MsgPackPeer();
    
    peer.on('open', (id) => {
      console.log('connected to peer server as ' + id);
    });
    
    // Data sent via this peer will be serialized using MsgPack
    peer.connect('some-peer-id').on('open', (conn) => {
      conn.send({ hello: 'world' });
    });