Skip to content

How to enable and disable P2P connections programmatically

Addressto enable and disable P2P connections programmatically

Peering can be disabled programmatically using the client-side JS call.

Examples

Turning OFF P2P connection

In case you wish to disable the P2P connections for a given user it suffices to run the following:

1
window.peer5 && peer5.configure({p2p: false});

After executing that call, the current Peer will no longer participate in the peering mesh network and thus requests will go through the regular network.

Turning ON P2P connection

Given the case you decided to re-enable the P2P connections, the same API needs to be call, this time with {p2p:true}.

As follows:

1
window.peer5 && peer5.configure({p2p: true});

Any requests made using peer5.Request after enabling P2P will fully utilize the Peer5 mesh network.

How to use this examples:

You can add to your page a script as the one below that checks every minute if peering should be enabled or not and configures Peer5 accordingly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<script>
var isPeer5Enabled = true;
setInterval(function () {
  fetch("http://example.com/api/peer5-status")
    .then(function (response) {
      return response.json()
    })
    .then(function (json) {
      if (!json || typeof json.peer5Enabled !== "boolean") return;
      if (json.peer5Enabled && !isPeer5Enabled) {
        window.peer5 && window.peer5.configure({p2p: true});
        isPeer5Enabled = true;
      } else if (!json.peer5Enabled && isPeer5Enabled) {
        window.peer5 && window.peer5.configure({p2p: false});
        isPeer5Enabled = false;
      }
    })
}, 60000)
</script>

More details

You can find more detailed explanations in our Client API document

For a more complete guide on how you can use this method, you can read the guide: Disabling Peer5 Programmatically