PeerJS Server Component

1.0.2 · active · verified Sun Apr 19

The `peer` package provides the server-side component for PeerJS, a WebRTC signaling library, enabling seamless peer-to-peer connections in web applications. It serves as the intermediary for PeerJS clients to discover each other and exchange crucial connection information before establishing a direct WebRTC link. The current stable version is 1.0.2, with active development progressing towards v1.1.0, evidenced by recent release candidates. This project maintains a steady release cadence, primarily focusing on dependency updates, bug fixes, and minor enhancements. Its key differentiator is its tight integration and compatibility with the PeerJS client library, offering a straightforward solution for deploying a WebRTC signaling server without requiring complex custom implementations. It also supports integration with existing Express applications, providing flexibility for deployment.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and run the PeerJS server using TypeScript, integrating it with an Express application to serve static content. It includes configuration for port and path via environment variables, basic error handling for port conflicts, and graceful shutdown.

import { PeerServer } from 'peer';
import express from 'express';
import { createServer } from 'http';
import path from 'path';

// Define the port and path for the PeerJS server, allowing environment variable overrides.
const PEER_PORT = process.env.PEER_PORT ? parseInt(process.env.PEER_PORT, 10) : 9000;
const PEER_PATH = process.env.PEER_PATH || '/myapp'; // Use a distinct path for isolation

// Create an Express application to serve static files or handle other API routes.
const app = express();

// Serve a basic static HTML file from a 'public' directory.
// Make sure to create a 'public' directory with an 'index.html' for this example to run fully.
app.use(express.static(path.join(__dirname, '../public')));

// Create an HTTP server that will host both the Express app and the PeerJS WebSocket server.
const httpServer = createServer(app);

// Initialize PeerJS server and attach it to the existing HTTP server.
// The `PeerServer` function creates an instance that listens for WebSocket connections.
const peerServer = PeerServer({
  port: PEER_PORT,
  path: PEER_PATH,
  allow_discovery: true, // Enables client discovery (optional, security consideration)
  // For production, consider adding key and cert for HTTPS
  // key: fs.readFileSync('path/to/key.pem'),
  // cert: fs.readFileSync('path/to/cert.pem'),
}, (server) => {
  console.log(`PeerJS server initialized.`);
  console.log(`  - WebSocket endpoint: ws://localhost:${PEER_PORT}${PEER_PATH}`);
  console.log(`  - Server ID: ${server.id}`);
});

// Listen on the specified port for HTTP and WebSocket connections.
httpServer.listen(PEER_PORT, () => {
  console.log(`HTTP server (for static content) listening on port ${PEER_PORT}`);
  console.log('Access the client at http://localhost:9000/index.html');
});

// Handle server errors
httpServer.on('error', (err: NodeJS.ErrnoException) => {
  if (err.code === 'EADDRINUSE') {
    console.error(`Port ${PEER_PORT} is already in use. Please choose another port or terminate the existing process.`);
  } else {
    console.error(`Server error: ${err.message}`);
  }
  process.exit(1);
});

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('Shutting down server...');
  peerServer.destroy(() => {
    httpServer.close(() => {
      console.log('Server gracefully shut down.');
      process.exit(0);
    });
  });
});

view raw JSON →