nostrrelays
v1.0.0
Published
Returns the best nostr relays for pub/sub
Maintainers
Readme
nostrrelays
Returns an ordered list of Nostr relay URLs best suited for pub/sub.
Features
- 🔍 Tests candidate relays by connecting via WebSocket
- 📡 Subscribes and publishes to verify readability and writeability
- ✅ NIP-20 OK validation - prefers relays that accept events
- ⚡ Measures latency and prioritizes fast relays
- 🛡️ Error tracking - avoids unreliable relays
- 📊 Intelligent scoring - ranks relays by quality
Installation
npm install nostrrelaysUsage
Basic Usage
import { getBestRelays } from 'nostrrelays';
// Get top 5 best relays
const relays = await getBestRelays();
console.log(relays);
// [
// {
// url: 'wss://relay.damus.io',
// writable: true,
// readable: true,
// latency: 234,
// errors: 0,
// score: 149.77,
// details: { ... }
// },
// ...
// ]
// Just get the URLs
const urls = relays.map(r => r.url);Advanced Options
const relays = await getBestRelays({
// Custom relay list to test (defaults to popular relays)
relays: [
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://nostr.wine'
],
// Timeout for each test in milliseconds
timeout: 5000,
// Maximum number of relays to return
maxRelays: 10,
// Only return writable relays (that accept events)
requireWritable: true,
// Only return readable relays (that serve events)
requireReadable: true,
// Test relays in parallel (faster)
parallel: true
});How It Works
The library tests each relay by:
- Connecting via WebSocket
- Subscribing (REQ) to test readability - waits for EOSE response
- Publishing a test event to verify writeability - waits for NIP-20 OK response
- Measuring latency for each operation
- Scoring relays based on:
- ✅ Writable (accepts events): +100 points
- ✅ Readable (serves events): +50 points
- ⚡ Low latency: better score
- ❌ Errors: -20 points each
Relay Result Object
Each relay in the returned array has the following properties:
{
url: 'wss://relay.damus.io', // Relay WebSocket URL
writable: true, // Can publish events
readable: true, // Can read events
latency: 234, // Average latency in ms
errors: 0, // Number of errors encountered
score: 149.77, // Quality score (higher is better)
details: { // Detailed metrics
connectLatency: 120,
subscribeLatency: 180,
publishLatency: 300
}
}Best Practices
⚠️ Note: This library provides best-effort relay selection. Relay policies, rate limits, and uptime may change. Results are based on point-in-time testing.
- Test relays periodically to get fresh results
- Use
timeoutappropriately based on your network conditions - Consider caching results to avoid excessive testing
- Handle cases where no relays meet your requirements
License
MIT
