⚡ WebRTC2 Quick Start: 5-Minute Sovereign Communication
From zero to peer-to-peer in 5 minutes
This guide gets you from installation to your first secure P2P connection in under 5 minutes. No cloud dependencies, no vendor lock-in, no surveillance infrastructure required.
🚀 Option 1: Instant Demo (2 Minutes)
Try WebRTC2 Now
Open two browser tabs and experience P2P communication:
<!DOCTYPE html>
<html>
<head>
<title>WebRTC2 Instant Demo</title>
<script src="https://cdn.webrtc2.com/client/latest.js"></script>
</head>
<body>
<div id="app">
<h1>🌐 WebRTC2 P2P Demo</h1>
<!-- Connection Setup -->
<div id="setup">
<input id="peerId" placeholder="Your Peer ID will appear here" readonly>
<input id="targetPeer" placeholder="Enter target peer ID">
<button onclick="connect()">Connect P2P</button>
</div>
<!-- Chat Interface -->
<div id="chat" style="display:none;">
<div id="messages"></div>
<input id="messageInput" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<button onclick="sendFile()">Send File</button>
</div>
</div>
<script>
// Initialize WebRTC2 client
const client = new WebRTC2.Client({
signalingServer: 'wss://demo.webrtc2.com/signaling'
});
// Generate and display peer ID
client.ready().then(() => {
document.getElementById('peerId').value = client.peerId;
console.log('🔑 Your Peer ID:', client.peerId);
});
// Connect to another peer
async function connect() {
const targetPeer = document.getElementById('targetPeer').value;
if (!targetPeer) return alert('Enter target peer ID');
try {
const connection = await client.connect(targetPeer);
document.getElementById('setup').style.display = 'none';
document.getElementById('chat').style.display = 'block';
// Handle incoming messages
connection.onMessage = (message) => {
addMessage(`Peer: ${message.content}`);
};
addMessage('✅ Connected securely via P2P!');
} catch (error) {
alert('Connection failed: ' + error.message);
}
}
// Send message
async function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message) return;
await client.sendMessage(message);
addMessage(`You: ${message}`);
input.value = '';
}
// Send file
async function sendFile() {
const input = document.createElement('input');
input.type = 'file';
input.onchange = async (e) => {
const file = e.target.files[0];
if (file) {
const transfer = await client.sendFile(file);
addMessage(`📎 Sending: ${file.name} (${file.size} bytes)`);
transfer.onProgress = (progress) => {
console.log(`Transfer progress: ${progress.percentage}%`);
};
}
};
input.click();
}
function addMessage(text) {
const messages = document.getElementById('messages');
const div = document.createElement('div');
div.textContent = text;
messages.appendChild(div);
messages.scrollTop = messages.scrollHeight;
}
</script>
</body>
</html>
Test Instructions:
- Save as
webrtc2-demo.html
- Open in two browser tabs
- Copy peer ID from tab 1 to tab 2
- Click "Connect P2P" in tab 2
- Start messaging and file sharing!
🛠️ Option 2: Development Setup (5 Minutes)
Install WebRTC2 SDK
For Web Applications:
# Using npm
npm install @webrtc2/client @webrtc2/crypto-web
# Using yarn
yarn add @webrtc2/client @webrtc2/crypto-web
# Using pnpm
pnpm add @webrtc2/client @webrtc2/crypto-web
For React Native:
npm install @webrtc2/client @webrtc2/crypto-expo
For Electron/Desktop:
npm install @webrtc2/client @webrtc2/crypto-electron
Basic Implementation
TypeScript/JavaScript Example:
import { WebRTC2Client } from '@webrtc2/client';
// Initialize client with your signaling server
const client = new WebRTC2Client({
signalingServer: 'wss://your-domain.com/signaling',
// Optional: Authentication
authentication: {
type: 'token',
token: 'your-auth-token'
},
// Optional: Encryption level
encryptionLevel: 'maximum',
// Optional: TURN/STUN servers
iceServers: [
{ urls: 'stun:your-domain.com:3478' },
{
urls: 'turn:your-domain.com:3478',
username: 'your-username',
credential: 'your-password'
}
]
});
// Wait for client to be ready
await client.ready();
console.log('🔑 Your Peer ID:', client.peerId);
// Connect to another peer
const connection = await client.connect('target-peer-id');
// Send messages
await connection.sendMessage('Hello from WebRTC2!');
// Handle incoming messages
connection.onMessage = (message) => {
console.log('📨 Received:', message.content);
};
// Send files (unlimited size)
const fileInput = document.getElementById('file-input');
fileInput.onchange = async (event) => {
const file = event.target.files[0];
const transfer = await connection.sendFile(file);
// Monitor transfer progress
transfer.onProgress = (progress) => {
console.log(`📁 Transfer: ${progress.percentage}%`);
};
transfer.onComplete = () => {
console.log('✅ File sent successfully!');
};
};
// Start video call
const mediaCall = await connection.startCall({
audio: true,
video: { width: 1280, height: 720 }
});
// Handle remote video stream
mediaCall.onRemoteStream = (stream) => {
const videoElement = document.getElementById('remote-video');
videoElement.srcObject = stream;
};
React Component Example
Modern React Hook:
import React, { useState, useEffect } from 'react';
import { useWebRTC2 } from '@webrtc2/react';
export function ChatComponent() {
const { client, isReady, connect, sendMessage, messages } = useWebRTC2({
signalingServer: 'wss://your-domain.com/signaling'
});
const [targetPeer, setTargetPeer] = useState('');
const [messageText, setMessageText] = useState('');
const [isConnected, setIsConnected] = useState(false);
const handleConnect = async () => {
try {
await connect(targetPeer);
setIsConnected(true);
} catch (error) {
console.error('Connection failed:', error);
}
};
const handleSendMessage = async () => {
if (messageText.trim()) {
await sendMessage(messageText);
setMessageText('');
}
};
if (!isReady) {
return <div>🔄 Initializing WebRTC2...</div>;
}
return (
<div className="webrtc2-chat">
<div className="peer-info">
<strong>Your Peer ID:</strong> {client.peerId}
</div>
{!isConnected ? (
<div className="connection-setup">
<input
type="text"
placeholder="Enter target peer ID"
value={targetPeer}
onChange={(e) => setTargetPeer(e.target.value)}
/>
<button onClick={handleConnect}>Connect P2P</button>
</div>
) : (
<div className="chat-interface">
<div className="messages">
{messages.map((message, index) => (
<div key={index} className="message">
<strong>{message.sender}:</strong> {message.content}
</div>
))}
</div>
<div className="message-input">
<input
type="text"
placeholder="Type your message..."
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
/>
<button onClick={handleSendMessage}>Send</button>
</div>
</div>
)}
</div>
);
}
🏗️ Option 3: Self-Hosted Infrastructure (10 Minutes)
Deploy Your Own Signaling Server
Using Docker (Recommended):
# Pull and run WebRTC2 signaling server
docker run -d \
--name webrtc2-signaling \
-p 8443:8443 \
-p 3478:3478/udp \
-e WEBRTC2_DOMAIN=your-domain.com \
-e WEBRTC2_SSL_EMAIL=admin@your-domain.com \
-v $(pwd)/config:/app/config \
-v $(pwd)/ssl:/app/ssl \
webrtc2/signaling-server:latest
# Check server status
curl -k https://localhost:8443/health
Manual Installation:
# Install Node.js 18+ and WebRTC2 server
npm install -g @webrtc2/server
# Create configuration
mkdir webrtc2-server && cd webrtc2-server
cat > config.yaml << EOF
server:
host: "0.0.0.0"
port: 8443
ssl:
enabled: true
selfSigned: true
signaling:
mode: "zero-knowledge"
crypto:
identityProvider: "self-sovereign"
encryptionLevel: "maximum"
logging:
level: "info"
EOF
# Start server
webrtc2-server --config config.yaml
TURN/STUN Server Setup
Using Coturn (for NAT traversal):
# Install coturn
sudo apt-get install coturn
# Configure coturn
sudo cat > /etc/turnserver.conf << EOF
listening-port=3478
tls-listening-port=5349
listening-ip=0.0.0.0
relay-ip=YOUR_SERVER_IP
external-ip=YOUR_SERVER_IP
realm=your-domain.com
server-name=your-domain.com
lt-cred-mech
user=webrtc2:your-secure-password
cert=/etc/ssl/certs/your-cert.pem
pkey=/etc/ssl/private/your-key.pem
cipher-list="ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS"
no-stdout-log
log-file=/var/log/turnserver.log
EOF
# Start TURN server
sudo systemctl enable coturn
sudo systemctl start coturn
📱 Platform-Specific Quick Starts
React Native Mobile App
Installation:
# Create new React Native project
npx react-native init WebRTC2MobileApp
cd WebRTC2MobileApp
# Install WebRTC2 dependencies
npm install @webrtc2/client @webrtc2/crypto-expo
npm install react-native-webrtc
# iOS additional setup
cd ios && pod install && cd ..
Basic Implementation:
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import { WebRTC2Client } from '@webrtc2/client';
export default function App() {
const [client, setClient] = useState<WebRTC2Client | null>(null);
const [peerId, setPeerId] = useState('');
const [targetPeer, setTargetPeer] = useState('');
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
initializeWebRTC2();
}, []);
const initializeWebRTC2 = async () => {
try {
const webrtcClient = new WebRTC2Client({
signalingServer: 'wss://your-domain.com/signaling',
platform: 'react-native'
});
await webrtcClient.ready();
setClient(webrtcClient);
setPeerId(webrtcClient.peerId);
} catch (error) {
Alert.alert('Error', 'Failed to initialize WebRTC2');
}
};
const connectToPeer = async () => {
if (!client || !targetPeer) return;
try {
const connection = await client.connect(targetPeer);
setIsConnected(true);
connection.onMessage = (message) => {
Alert.alert('Message Received', message.content);
};
} catch (error) {
Alert.alert('Connection Failed', error.message);
}
};
return (
<View style={{ flex: 1, padding: 20, justifyContent: 'center' }}>
<Text style={{ fontSize: 18, marginBottom: 20 }}>
🌐 WebRTC2 Mobile Demo
</Text>
<Text>Your Peer ID: {peerId}</Text>
<TextInput
style={{ borderWidth: 1, padding: 10, marginVertical: 10 }}
placeholder="Enter target peer ID"
value={targetPeer}
onChangeText={setTargetPeer}
/>
<TouchableOpacity
style={{ backgroundColor: '#007AFF', padding: 15, borderRadius: 5 }}
onPress={connectToPeer}
disabled={!client || isConnected}
>
<Text style={{ color: 'white', textAlign: 'center' }}>
{isConnected ? '✅ Connected' : 'Connect P2P'}
</Text>
</TouchableOpacity>
</View>
);
}
Electron Desktop App
Setup:
# Create Electron app
npm create electron-app webrtc2-desktop
cd webrtc2-desktop
# Install WebRTC2
npm install @webrtc2/client @webrtc2/crypto-electron
Main Process Integration:
// src/main.ts
import { app, BrowserWindow, ipcMain } from 'electron';
import { WebRTC2Client } from '@webrtc2/client';
let mainWindow: BrowserWindow;
let webrtcClient: WebRTC2Client;
const createWindow = async () => {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await mainWindow.loadFile('index.html');
// Initialize WebRTC2 in main process
webrtcClient = new WebRTC2Client({
signalingServer: 'wss://your-domain.com/signaling',
platform: 'electron'
});
await webrtcClient.ready();
// Send peer ID to renderer
mainWindow.webContents.send('peer-id', webrtcClient.peerId);
};
// Handle IPC messages from renderer
ipcMain.handle('connect-peer', async (event, targetPeerId) => {
try {
const connection = await webrtcClient.connect(targetPeerId);
return { success: true, peerId: targetPeerId };
} catch (error) {
return { success: false, error: error.message };
}
});
app.whenReady().then(createWindow);
🔧 Advanced Configuration
Production Configuration
Enterprise-Grade Setup:
const client = new WebRTC2Client({
// Signaling server configuration
signalingServer: 'wss://signaling.your-company.com/ws',
// Authentication
authentication: {
type: 'certificate',
certificate: yourClientCertificate,
privateKey: yourPrivateKey
},
// Security configuration
encryptionLevel: 'maximum',
identityProvider: 'self-sovereign',
// Network configuration
iceServers: [
{ urls: 'stun:stun.your-company.com:3478' },
{
urls: 'turn:turn.your-company.com:3478',
username: 'webrtc2-user',
credential: 'secure-password'
}
],
// Performance optimization
adaptiveBitrate: true,
hardwareAcceleration: true,
// Compliance settings
auditLogging: true,
dataRetention: 'never',
geoRestriction: 'US-only',
// Federation settings
federatedServers: [
'wss://partner1.com/signaling',
'wss://partner2.com/signaling'
],
// Plugin configuration
plugins: [
new AIProductivityPlugin(),
new CompliancePlugin({ mode: 'HIPAA' })
]
});
Healthcare (HIPAA) Configuration
HIPAA-Compliant Setup:
const hipaaClient = new WebRTC2Client({
signalingServer: 'wss://hipaa-signaling.hospital.com/ws',
// HIPAA compliance settings
complianceMode: 'HIPAA',
encryptionLevel: 'FIPS-140-2',
auditLogging: true,
dataRetention: 'never',
geoRestriction: 'US-only',
// Enhanced security
authentication: {
type: 'multi-factor',
methods: ['certificate', 'hardware-key']
},
// Session management
sessionTimeout: 900, // 15 minutes
automaticLogoff: true,
// Network restrictions
allowedNetworks: ['10.0.0.0/8', '192.168.0.0/16'],
// Breach detection
anomalyDetection: true,
intrusionPrevention: true
});
🚨 Troubleshooting Common Issues
Connection Problems
Issue: "Failed to establish P2P connection"
// Debug connection issues
client.onConnectionError = (error) => {
console.error('Connection error:', error);
// Check common issues
if (error.code === 'SIGNALING_FAILED') {
console.log('❌ Signaling server unreachable');
console.log('✅ Check server URL and network connectivity');
}
if (error.code === 'ICE_FAILED') {
console.log('❌ NAT traversal failed');
console.log('✅ Configure TURN server or check firewall');
}
if (error.code === 'AUTH_FAILED') {
console.log('❌ Authentication failed');
console.log('✅ Check authentication credentials');
}
};
// Enable debug logging
client.setLogLevel('debug');
Issue: "Peer not found"
// Verify peer is online
const isOnline = await client.isPeerOnline('target-peer-id');
if (!isOnline) {
console.log('❌ Target peer is offline');
console.log('✅ Ensure both peers are connected to same signaling server');
}
Performance Issues
Issue: "Slow file transfer"
// Optimize file transfer
const transfer = await connection.sendFile(file, {
chunkSize: 'adaptive', // Adaptive chunk sizing
parallelChunks: 4, // Parallel transfer
compression: true, // Enable compression
priorityMode: 'speed' // Optimize for speed
});
Issue: "Poor video quality"
// Optimize video quality
const call = await connection.startCall({
video: {
width: 1280,
height: 720,
frameRate: 30,
bitrate: 'adaptive' // Adaptive bitrate
},
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
});
// Monitor connection quality
call.onStatsUpdate = (stats) => {
if (stats.packetsLost > 0.05) {
// Reduce quality if packet loss is high
call.adjustQuality('medium');
}
};
📚 Next Steps
Learning Resources
Documentation:
Example Applications:
Community:
Production Deployment
Ready for production?
From prototype to production in minutes. From centralized to sovereign in seconds.
Your first P2P connection is just 5 minutes away. Your communication sovereignty starts now.