Skip to main content

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 install 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

OptionTypeDefaultDescription
portnumber9000Port to listen on
pathstring"/"Path prefix
keystring"peerjs"API key clients must provide
proxiedbooleanfalseSet true if behind a reverse proxy
expire_timeoutnumber5000Timeout for messages (ms)
alive_timeoutnumber60000Timeout for heartbeat (ms)
allow_discoverybooleanfalseAllow 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: true on the client.
  • TURN servers: PeerServer only handles signaling. You still need TURN servers for peers behind symmetric NATs. See the FAQ for configuration.