PeerServer
PeerJS uses a signaling server to broker connections between peers. By default, it connects to the free PeerJS Cloud server. For production, you can host your own.
Quick Start
- npm
- Yarn
- pnpm
- Bun
npm install peer
yarn add peer
pnpm add peer
bun add peer
server.js
const { PeerServer } = require("peer");
const server = PeerServer({ port: 9000, path: "/myapp" });
server.on("connection", (client) => {
console.log("Client connected:", client.getId());
});
server.on("disconnect", (client) => {
console.log("Client disconnected:", client.getId());
});
node server.js
Connect from the Client
Point your Peer to your server:
const peer = new Peer({
host: "localhost",
port: 9000,
path: "/myapp",
secure: false, // Use true with HTTPS
});
Server Options
| Option | Type | Default | Description |
|---|---|---|---|
port | number | 9000 | Port to listen on |
path | string | "/" | Path prefix |
key | string | "peerjs" | API key clients must provide |
proxied | boolean | false | Set true if behind a reverse proxy |
expire_timeout | number | 5000 | Timeout for messages (ms) |
alive_timeout | number | 60000 | Timeout for heartbeat (ms) |
allow_discovery | boolean | false | Allow clients to list all peer IDs |
Express Integration
PeerServer can be mounted as Express middleware:
const express = require("express");
const { ExpressPeerServer } = require("peer");
const app = express();
const server = app.listen(9000);
const peerServer = ExpressPeerServer(server, {
path: "/myapp",
});
app.use("/peerjs", peerServer);
peerServer.on("connection", (client) => {
console.log("Connected:", client.getId());
});
Docker
Run PeerServer with Docker:
docker run -p 9000:9000 peerjs/peerjs-server
Or with custom options:
docker run -p 9000:9000 peerjs/peerjs-server \
--port 9000 \
--path /myapp \
--key myapikey
Production Considerations
- HTTPS: Always use SSL in production. Set
secure: trueon the client. - TURN servers: PeerServer only handles signaling. You still need TURN servers for peers behind symmetric NATs. See the FAQ for configuration.