Convert Figma logo to code with AI

peers logopeerjs

Simple peer-to-peer with WebRTC.

12,311
1,425
12,311
188

Top Related Projects

13,895

WebRTC Web demos and samples

📡 Simple WebRTC video, voice, and data channels

WebRTC, WebRTC and WebRTC. Everything here is all about WebRTC!!

4,158

appr.tc has been shutdown. Please use the Dockerfile to run your own test/dev instance.

11,072

coturn TURN server project

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

Quick Overview

PeerJS is a JavaScript library that provides a simple abstraction on top of WebRTC, allowing developers to create peer-to-peer data, voice, and video connections in the browser. It aims to provide a complete, configurable, and easy-to-use peer-to-peer connection API.

Pros

  • Simplifies WebRTC: PeerJS abstracts away the complexity of WebRTC, making it easier for developers to implement peer-to-peer communication in their applications.
  • Cross-browser Compatibility: PeerJS works across all major browsers, including Chrome, Firefox, Safari, and Edge.
  • Flexible and Customizable: PeerJS allows developers to customize various aspects of the peer-to-peer connection, such as signaling server, data channels, and media constraints.
  • Active Development and Community: The project has an active community, with regular updates and a responsive team of maintainers.

Cons

  • Dependency on Signaling Server: PeerJS requires a signaling server to establish the initial peer-to-peer connection, which can be a potential point of failure or introduce additional complexity.
  • Limited Control over WebRTC: While PeerJS simplifies WebRTC, it also limits the level of control developers have over the underlying WebRTC implementation.
  • Performance Concerns: Depending on the use case and network conditions, PeerJS may not provide the same level of performance as a custom WebRTC implementation.
  • Limited Documentation: The project's documentation, while generally good, could be more comprehensive and provide more detailed examples.

Code Examples

// Establishing a peer-to-peer connection
const peer = new Peer();

peer.on('open', (id) => {
  console.log('My peer ID is:', id);
});

peer.on('connection', (conn) => {
  conn.on('data', (data) => {
    console.log('Received', data);
  });

  conn.on('open', () => {
    conn.send('Hello!');
  });
});

This code demonstrates how to create a new Peer instance, listen for the open event to get the peer's ID, and handle incoming connections and data.

// Connecting to a remote peer
const conn = peer.connect('remote-peer-id');

conn.on('open', () => {
  conn.send('Hello, remote peer!');
});

conn.on('data', (data) => {
  console.log('Received from remote peer:', data);
});

This code shows how to connect to a remote peer by providing their peer ID, and then send and receive data through the established connection.

// Establishing a video call
const call = peer.call('remote-peer-id', localStream);

call.on('stream', (remoteStream) => {
  // Display the remote video stream
  videoElement.srcObject = remoteStream;
});

This code demonstrates how to initiate a video call with a remote peer by providing their peer ID and a local video stream. The remote video stream is then displayed in the videoElement.

Getting Started

To get started with PeerJS, follow these steps:

  1. Install the PeerJS library using npm or yarn:
npm install peerjs
  1. Create a new Peer instance and listen for the open event to get the peer's ID:
const Peer = require('peerjs');
const peer = new Peer();

peer.on('open', (id) => {
  console.log('My peer ID is:', id);
});
  1. To connect to a remote peer, use the connect() method and provide the remote peer's ID:
const conn = peer.connect('remote-peer-id');

conn.on('open', () => {
  conn.send('Hello, remote peer!');
});

conn.on('data', (data) => {
  console.log('Received from remote peer:', data);
});
  1. To establish a video call, use the call() method and provide the remote peer's ID and a local video stream:
const call = peer.call('remote-peer-id', localStream);

call.on('stream', (remoteStream) => {
  // Display the remote video

Competitor Comparisons

13,895

WebRTC Web demos and samples

Pros of WebRTC Samples

  • Comprehensive collection of WebRTC examples covering various use cases
  • Regularly updated with the latest WebRTC features and best practices
  • Maintained by the official WebRTC project, ensuring high-quality and accurate implementations

Cons of WebRTC Samples

  • Focuses on raw WebRTC implementation, requiring more setup and configuration
  • Steeper learning curve for beginners compared to PeerJS's simplified API
  • Lacks built-in signaling and connection management features

Code Comparison

WebRTC Samples (raw WebRTC):

const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addTrack(videoTrack, stream);
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);

PeerJS:

const peer = new Peer();
const call = peer.call('remote-peer-id', stream);
call.on('stream', (remoteStream) => {
  // Handle remote stream
});

PeerJS simplifies the connection process with a higher-level API, while WebRTC Samples demonstrates raw WebRTC implementation, offering more control but requiring more code.

📡 Simple WebRTC video, voice, and data channels

Pros of simple-peer

  • Lightweight and focused solely on WebRTC data channel functionality
  • Easier to integrate into existing projects due to its simplicity
  • More actively maintained with frequent updates and bug fixes

Cons of simple-peer

  • Lacks built-in signaling server functionality
  • Does not provide as many high-level abstractions as PeerJS
  • May require more manual configuration for complex use cases

Code Comparison

simple-peer:

const peer = new SimplePeer({ initiator: true })
peer.on('signal', data => {
  // send signal data to peer
})
peer.on('data', data => {
  console.log('Received data:', data)
})

PeerJS:

const peer = new Peer()
const conn = peer.connect('peer-id')
conn.on('open', () => {
  conn.send('Hello!')
})
conn.on('data', data => {
  console.log('Received data:', data)
})

Both libraries provide similar functionality for peer-to-peer communication, but simple-peer focuses on lower-level WebRTC operations, while PeerJS offers a higher-level abstraction with built-in signaling and connection management. The choice between them depends on the specific requirements of your project and the level of control you need over the WebRTC implementation.

WebRTC, WebRTC and WebRTC. Everything here is all about WebRTC!!

Pros of WebRTC-Experiment

  • More comprehensive set of WebRTC demos and examples
  • Includes additional features like screen sharing and audio/video recording
  • Offers a wider range of WebRTC-related utilities and helper functions

Cons of WebRTC-Experiment

  • Less focused on peer-to-peer networking compared to PeerJS
  • May have a steeper learning curve due to its broader scope
  • Not as actively maintained as PeerJS (last update was in 2021)

Code Comparison

WebRTC-Experiment:

connection.openOrJoin('room-id', function(isRoomCreated, roomid, error) {
    if (error) {
        console.error(error);
    }
    else {
        console.log('Connected to room:', roomid);
    }
});

PeerJS:

const peer = new Peer();
peer.on('open', (id) => {
    const conn = peer.connect('remote-peer-id');
    conn.on('open', () => {
        conn.send('Hello!');
    });
});

Both libraries provide abstractions for WebRTC connections, but PeerJS focuses more on simple peer-to-peer networking, while WebRTC-Experiment offers a broader range of WebRTC functionalities. PeerJS may be more suitable for straightforward P2P applications, while WebRTC-Experiment could be better for complex WebRTC projects requiring additional features.

4,158

appr.tc has been shutdown. Please use the Dockerfile to run your own test/dev instance.

Pros of AppRTC

  • More comprehensive WebRTC implementation with additional features
  • Better suited for complex, multi-user applications
  • Includes server-side components for signaling and TURN functionality

Cons of AppRTC

  • Steeper learning curve due to increased complexity
  • Requires more setup and infrastructure compared to PeerJS
  • Less suitable for simple peer-to-peer applications

Code Comparison

AppRTC (JavaScript):

var startTime = window.performance.now();
var call = new Call(config_);
call.start(roomId);
this.call_ = call;

call.onlocalstreamadded = this.onLocalStreamAdded_.bind(this);

PeerJS (JavaScript):

const peer = new Peer();
peer.on('open', (id) => {
  const conn = peer.connect('destination-peer-id');
  conn.on('open', () => {
    conn.send('Hello!');
  });
});

AppRTC provides a more comprehensive setup for WebRTC calls, including room management and additional event handling. PeerJS offers a simpler API for basic peer-to-peer connections, making it easier to get started with WebRTC functionality in smaller projects.

Both libraries serve different use cases, with AppRTC being more suitable for complex, multi-user applications, while PeerJS excels in simplicity for basic peer-to-peer communication scenarios.

11,072

coturn TURN server project

Pros of coturn

  • More comprehensive TURN/STUN server implementation
  • Supports a wider range of protocols and features
  • Better suited for large-scale deployments and enterprise use cases

Cons of coturn

  • More complex setup and configuration
  • Requires more server resources to run
  • Steeper learning curve for beginners

Code comparison

coturn (configuration example):

listening-port=3478
listening-ip=0.0.0.0
relay-ip=0.0.0.0
external-ip=203.0.113.10
realm=example.com

peerjs (client-side usage):

const peer = new Peer('someid', {
  host: 'localhost',
  port: 9000,
  path: '/myapp'
});

Summary

coturn is a full-featured TURN/STUN server implementation, offering extensive functionality and scalability for WebRTC applications. It's ideal for large-scale deployments but requires more setup and resources.

peerjs, on the other hand, is a simpler peer-to-peer WebRTC library focused on ease of use for developers. It abstracts away much of the complexity of WebRTC connections but may not be as suitable for complex or large-scale scenarios.

Choose coturn for robust, scalable TURN/STUN server needs, and peerjs for quick, easy peer-to-peer WebRTC implementations in JavaScript applications.

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

Pros of Jitsi Meet

  • Full-featured video conferencing solution with a complete UI
  • Supports large-scale meetings and advanced features like screen sharing
  • Active development with frequent updates and a large community

Cons of Jitsi Meet

  • More complex setup and deployment compared to PeerJS
  • Heavier resource usage due to its comprehensive feature set
  • Steeper learning curve for developers new to WebRTC

Code Comparison

Jitsi Meet (JavaScript):

const options = {
    roomName: 'MyConferenceRoom',
    width: 700,
    height: 700,
    parentNode: document.querySelector('#meet')
};
const api = new JitsiMeetExternalAPI(domain, options);

PeerJS (JavaScript):

const peer = new Peer();
const conn = peer.connect('another-peers-id');
conn.on('open', () => {
    conn.send('Hello!');
});

Jitsi Meet provides a higher-level API for creating video conferences, while PeerJS offers a more low-level approach for peer-to-peer connections. Jitsi Meet is better suited for full-featured video conferencing applications, whereas PeerJS is ideal for simpler peer-to-peer communication scenarios or as a building block for custom WebRTC applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PeerJS: Simple peer-to-peer with WebRTC

Backers on Open Collective Sponsors on Open Collective Discord

PeerJS provides a complete, configurable, and easy-to-use peer-to-peer API built on top of WebRTC, supporting both data channels and media streams.

Live Example

Here's an example application that uses both media and data connections: https://glitch.com/~peerjs-video. The example also uses its own PeerServer.


Special Announcement:

We now have a Discord Channel
There we plan to discuss roadmaps, feature requests, and more
Join us today


Setup

Include the library

with npm: npm install peerjs

with yarn: yarn add peerjs

// The usage -
import { Peer } from "peerjs";

Create a Peer

const peer = new Peer("pick-an-id");
// You can pick your own id or omit the id if you want to get a random one from the server.

Data connections

Connect

const conn = peer.connect("another-peers-id");
conn.on("open", () => {
	conn.send("hi!");
});

Receive

peer.on("connection", (conn) => {
	conn.on("data", (data) => {
		// Will print 'hi!'
		console.log(data);
	});
	conn.on("open", () => {
		conn.send("hello!");
	});
});

Media calls

Call

navigator.mediaDevices.getUserMedia(
	{ video: true, audio: true },
	(stream) => {
		const call = peer.call("another-peers-id", stream);
		call.on("stream", (remoteStream) => {
			// Show stream in some <video> element.
		});
	},
	(err) => {
		console.error("Failed to get local stream", err);
	},
);

Answer

peer.on("call", (call) => {
	navigator.mediaDevices.getUserMedia(
		{ video: true, audio: true },
		(stream) => {
			call.answer(stream); // Answer the call with an A/V stream.
			call.on("stream", (remoteStream) => {
				// Show stream in some <video> element.
			});
		},
		(err) => {
			console.error("Failed to get local stream", err);
		},
	);
});

Running tests

npm test

Browser support

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

We test PeerJS against these versions of Chrome, Edge, Firefox, and Safari with BrowserStack to ensure compatibility. It may work in other and older browsers, but we don't officially support them. Changes to browser support will be a breaking change going forward.

[!NOTE] Firefox 102+ is required for CBOR / MessagePack support.

FAQ

Q. I have a message Critical dependency: the request of a dependency is an expression in browser's console

A. The message occurs when you use PeerJS with Webpack. It is not critical! It relates to Parcel https://github.com/parcel-bundler/parcel/issues/2883 We'll resolve it when updated to Parcel V2.

Links

Documentation / API Reference

PeerServer

Discuss PeerJS on our Telegram Channel

Changelog

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

PeerJS is licensed under the MIT License.

NPM DownloadsLast 30 Days