{"id":11539,"library":"peer","title":"PeerJS Server Component","description":"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.","status":"active","version":"1.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/peers/peerjs-server","tags":["javascript","peerjs","webrtc","p2p","rtc","typescript"],"install":[{"cmd":"npm install peer","lang":"bash","label":"npm"},{"cmd":"yarn add peer","lang":"bash","label":"yarn"},{"cmd":"pnpm add peer","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for handling HTTP requests, serving static files, and integrating the PeerJS server with existing web applications.","package":"express"},{"reason":"The underlying WebSocket library for real-time communication between clients and the PeerJS server, updated to v8 in 1.0.0.","package":"ws"}],"imports":[{"note":"Since v1.0.0, the package primarily targets ESM environments. While CommonJS might still work, ESM is the recommended and best-supported import method for Node.js versions >=14.","wrong":"const PeerServer = require('peer').PeerServer;","symbol":"PeerServer","correct":"import { PeerServer } from 'peer';"},{"note":"Import the `ServerOptions` interface for type-checking and autocompletion when configuring the PeerServer.","symbol":"ServerOptions","correct":"import { ServerOptions } from 'peer';"},{"note":"PeerJS server can be integrated into an existing Express application. Ensure Express is imported correctly.","wrong":"const express = require('express');","symbol":"Application","correct":"import express, { Application } from 'express';"}],"quickstart":{"code":"import { PeerServer } from 'peer';\nimport express from 'express';\nimport { createServer } from 'http';\nimport path from 'path';\n\n// Define the port and path for the PeerJS server, allowing environment variable overrides.\nconst PEER_PORT = process.env.PEER_PORT ? parseInt(process.env.PEER_PORT, 10) : 9000;\nconst PEER_PATH = process.env.PEER_PATH || '/myapp'; // Use a distinct path for isolation\n\n// Create an Express application to serve static files or handle other API routes.\nconst app = express();\n\n// Serve a basic static HTML file from a 'public' directory.\n// Make sure to create a 'public' directory with an 'index.html' for this example to run fully.\napp.use(express.static(path.join(__dirname, '../public')));\n\n// Create an HTTP server that will host both the Express app and the PeerJS WebSocket server.\nconst httpServer = createServer(app);\n\n// Initialize PeerJS server and attach it to the existing HTTP server.\n// The `PeerServer` function creates an instance that listens for WebSocket connections.\nconst peerServer = PeerServer({\n  port: PEER_PORT,\n  path: PEER_PATH,\n  allow_discovery: true, // Enables client discovery (optional, security consideration)\n  // For production, consider adding key and cert for HTTPS\n  // key: fs.readFileSync('path/to/key.pem'),\n  // cert: fs.readFileSync('path/to/cert.pem'),\n}, (server) => {\n  console.log(`PeerJS server initialized.`);\n  console.log(`  - WebSocket endpoint: ws://localhost:${PEER_PORT}${PEER_PATH}`);\n  console.log(`  - Server ID: ${server.id}`);\n});\n\n// Listen on the specified port for HTTP and WebSocket connections.\nhttpServer.listen(PEER_PORT, () => {\n  console.log(`HTTP server (for static content) listening on port ${PEER_PORT}`);\n  console.log('Access the client at http://localhost:9000/index.html');\n});\n\n// Handle server errors\nhttpServer.on('error', (err: NodeJS.ErrnoException) => {\n  if (err.code === 'EADDRINUSE') {\n    console.error(`Port ${PEER_PORT} is already in use. Please choose another port or terminate the existing process.`);\n  } else {\n    console.error(`Server error: ${err.message}`);\n  }\n  process.exit(1);\n});\n\n// Graceful shutdown\nprocess.on('SIGINT', () => {\n  console.log('Shutting down server...');\n  peerServer.destroy(() => {\n    httpServer.close(() => {\n      console.log('Server gracefully shut down.');\n      process.exit(0);\n    });\n  });\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate your project to use ES module import syntax (`import ... from 'peer'`) and ensure your Node.js environment is configured for ESM (e.g., using `\"type\": \"module\"` in `package.json` or `.mjs` file extensions). Review `ws` v8 breaking changes if upgrading from older versions.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Consider running the PeerJS server on a non-privileged port (e.g., 9000 as in the quickstart) and use a reverse proxy like Nginx or Caddy to forward requests from standard HTTP/HTTPS ports. Ensure your proxy correctly handles WebSocket connections.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For production deployments, consider setting `allow_discovery: false` to disable ID listing. Implement your own secure mechanism for clients to exchange Peer IDs, such as a separate authentication service or direct sharing.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Add `\"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.","cause":"Your Node.js project is likely running in CommonJS mode, but `peer` v1.0.0+ uses ES Module syntax.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Change 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).","cause":"Another process is already using the port that your PeerJS server is trying to bind to (e.g., port 9000).","error":"Error: listen EADDRINUSE: address already in use :::9000"},{"fix":"Verify 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.","cause":"The client-side PeerJS configuration (host, port, path) does not match the server-side configuration, or a firewall is blocking the connection.","error":"WebSocket connection to 'ws://localhost:9000/peerjs?id=...' failed: Error during WebSocket handshake: Unexpected response code: 400"}],"ecosystem":"npm"}