Best Practices
import { Relay } from "nostr-tools/relay";
// Configuration constants
const RELAY_URL = "wss://dev-relay.dephy.dev";
const RECONNECT_DELAY_INITIAL_MS = 1000; // Initial reconnect delay (1 second)
const RECONNECT_DELAY_MAX_MS = 30000; // Maximum reconnect delay (30 seconds)
const RECONNECT_MAX_ATTEMPTS = 10; // Maximum reconnection attempts (optional)
// Global variables to manage connection state
let relay: Relay | null = null; // Active relay connection
let reconnectAttempts = 0; // Track number of reconnection attempts
let reconnectDelay = RECONNECT_DELAY_INITIAL_MS; // Current reconnect delay
/**
* Establishes connection to the Nostr relay and sets up event subscription.
* Handles automatic reconnection on failure.
*/
async function connectToRelay() {
try {
console.log(`Connecting to relay: ${RELAY_URL}...`);
// Attempt to connect to the relay
relay = await Relay.connect(RELAY_URL);
// Reset reconnection state on successful connection
reconnectAttempts = 0;
reconnectDelay = RECONNECT_DELAY_INITIAL_MS;
console.log("Connected to relay. Subscribing to events...");
// Subscribe to events matching the specified filter
relay.subscribe(
[
{
kinds: [1573], // Event kind (1573 for custom messages)
since: Math.floor(Date.now() / 1000), // Timestamp in seconds
"#s": ["hello_session"], // 's' tag filter
"#p": ["receiver_pubkey"], // 'p' tag filter
},
],
{
// Callback for received events
onevent: (event) => {
console.log("Received:", event.content);
},
}
);
/**
* Handle connection closure.
* This callback triggers when the relay intentionally closes the connection.
*/
relay.onclose = () => {
console.log("Connection closed by relay. Attempting to reconnect...");
scheduleReconnect();
};
} catch (err) {
// Handle initial connection failures
console.error("Initial connection failed:", err);
scheduleReconnect();
}
}
/**
* Schedules a reconnection attempt using exponential backoff.
* Increases delay between attempts up to RECONNECT_DELAY_MAX_MS.
*/
function scheduleReconnect() {
// Stop reconnecting after maximum attempts
if (reconnectAttempts >= RECONNECT_MAX_ATTEMPTS) {
console.error("Maximum reconnection attempts reached. Terminating.");
return;
}
reconnectAttempts++;
console.log(`Next reconnection attempt in ${reconnectDelay / 1000} seconds... (Attempt ${reconnectAttempts})`);
// Schedule reconnection with increasing delay
setTimeout(() => {
connectToRelay();
// Exponential backoff: double delay each time (capped at max delay)
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_DELAY_MAX_MS);
}, reconnectDelay);
}
// Graceful shutdown handler (e.g., Ctrl+C)
process.on("SIGINT", () => {
console.log("Terminating gracefully...");
if (relay) {
relay.close(); // Properly close the connection
}
process.exit(0); // Exit with success code
});
// Start initial connection
connectToRelay();Last updated

