Rafał Lorenz edited this page Jan 30, 2018 · 3 revisions

Plugins are factories for middleware allowing you to create more complicated logic used by peer-cdn.

There are 4 default plugins:

1. CachePlugin

Stores fetch responses in cache later to be used to share using WebRTC with other peers.

2. PeerPlugin

This is where main logic of peer-cdn is handled. Currently due to lack of support for WebRTC in the service workers is used with DelegatePlugin to be handled on client side. Creates middleware which asks other connected peer for a given resource and if found downloads it from other peers instead of server.

3. NetworkPlugin

Meant to be used as a last middleware simply fetching response from server.

3. DelegatePlugin

Allows you to delegate work meant to be done by plugin in this place to a service worker. This is done with the use of a MessageChannel allowing service worker and client to communicate. When using this plugin you are able to addEventListener on message where you an expect to get requested url.

  // since sw does not support webrtc yet
  // this is workaround to use it
  // we use PeerPlugin on client side
  const peerPlugin = new PeerPlugin({
    cacheName: CachePlugin.peerfetch + 1,
    timeoutAfter: 3000,
    servers: {
      iceServers: [
          url: "stun:"
    constraints: {
      ordered: true

  // Set up a listener for messages posted from the service worker.
  // The service worker is set to post a message to specific client only
  // so you should see this message event fire once.
  // You can force it to fire again by visiting this page in an Incognito window.
  navigator.serviceWorker.addEventListener('message', function (event) {
    const request = new Request(;
    // mock sw event wrapping request with object
    const middleware = peerPlugin.getMiddleware({ request });

    // run get method of a created middleware
      .then(function (response) {
        // return response to a service worker
      .catch(function (error) {
        // return response to a service worker
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.