PeerJS Server Component
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
-
SyntaxError: Cannot use import statement outside a module
cause Your Node.js project is likely running in CommonJS mode, but `peer` v1.0.0+ uses ES Module syntax.fixAdd `"type": "module"` to your `package.json` file, or rename your server file to have a `.mjs` extension. Ensure all `require()` statements are converted to `import` statements. -
Error: listen EADDRINUSE: address already in use :::9000
cause Another process is already using the port that your PeerJS server is trying to bind to (e.g., port 9000).fixChange the `PEER_PORT` environment variable or the hardcoded port in your server configuration to an available port. Alternatively, identify and terminate the process currently using that port (e.g., `lsof -i :9000` on Linux/macOS or `netstat -ano | findstr :9000` on Windows). -
WebSocket connection to 'ws://localhost:9000/peerjs?id=...' failed: Error during WebSocket handshake: Unexpected response code: 400
cause The client-side PeerJS configuration (host, port, path) does not match the server-side configuration, or a firewall is blocking the connection.fixVerify that the `host`, `port`, and `path` parameters in your client-side `new Peer({...})` constructor exactly match the `PeerServer` configuration on your Node.js server. Ensure no firewalls are blocking connections to the specified port.
Warnings
- breaking Version 1.0.0 of `peer` (peerjs-server) introduced a shift towards ESM-only environments, which may break applications still relying on CommonJS `require()` syntax. Additionally, the underlying WebSocket library `ws` was updated to v8.
- gotcha Running the PeerJS server on well-known ports (e.g., 80 or 443) often requires elevated privileges or careful reverse proxy configuration. Node.js applications typically run as unprivileged users.
- gotcha The `allow_discovery: true` option (demonstrated in quickstart) enables clients to list all active Peer IDs on the server. While convenient for development, it can be a privacy and security concern in production environments.
Install
-
npm install peer -
yarn add peer -
pnpm add peer
Imports
- PeerServer
const PeerServer = require('peer').PeerServer;import { PeerServer } from 'peer'; - ServerOptions
import { ServerOptions } from 'peer'; - Application
const express = require('express');import express, { Application } from 'express';
Quickstart
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);
});
});
});