Skip to main content

P2P Networking with GUN

Learn how to build peer-to-peer mesh networks with GUN. This guide covers relay servers, peer discovery, WebRTC connections, and distributed architecture patterns.

Understanding GUN’s Network Architecture

GUN uses a mesh network topology where:
  • Peers connect directly to each other
  • Data syncs automatically across all peers
  • No single point of failure
  • Works offline with automatic sync when reconnected
  • Optional relay servers for peer discovery

Network Topology

Setting Up a Basic P2P Network

Client-Side Only (Browser-to-Browser)

Simplest setup using public relay servers:

With Local Relay Server

For better control and performance:

Building a Relay Server

Simple HTTP Relay

Basic relay server using Node.js:
Run it:

Express.js Integration

Integrate with an existing Express app:

Production Relay with Clustering

High-availability relay with clustering:
Run with environment variables:

Peer Discovery

Static Peer Configuration

Dynamic Peer Discovery

WebRTC Peer Discovery

Network Status and Monitoring

Check Connection Status

Network Statistics

Health Check Endpoint

Offline-First Architecture

Local-First with Background Sync

Service Worker for Offline Support

Data Replication Strategies

Full Replication

Selective Replication

Time-Based Sync

Security and Access Control

Peer Whitelisting

Rate Limiting

Authenticated Relays

Deployment Options

Docker Deployment

Kubernetes Deployment

Systemd Service

Best Practices

  1. Use Multiple Relays - Don’t rely on a single server
  2. Enable HTTPS - Secure your connections
  3. Monitor Health - Track peer connections and sync status
  4. Implement Backups - Regularly backup relay data
  5. Rate Limit - Protect against abuse
  6. Geographic Distribution - Place relays near users
  7. Graceful Degradation - Work offline when network unavailable

Troubleshooting

Connection Issues

Network Inspector

Next Steps

Chat App

Build a P2P chat application

Security

Learn about securing your network

Storage Adapters

Persist data with custom adapters

Scaling

Scale your GUN network