service-worker-gateway
An IPFS gateway fully running on a Service Worker, in order to serve all your IPFS urls directly!
Lead Maintainer
Installation
> npm i service-worker-gateway
Testing the example
Run the following commands:
> git clone https://github.com/ipfs-shipyard/service-worker-gateway.git> cd service-worker-gateway> npm install> cd example> npm install> npm run build> npm run start
Usage
The service worker gateway will get in action when specifc HTTP requests occur.
/ipfs/{HASH}
- Get the content of the file represented by the Hash/stats
- Get the current stats of the IPFS Node running in the service worker
Service Worker running on IPFS node
The service worker code lives in src/index.js
. This is the code that will run as a service worker. It boots up an IPFS node, responds to requests and exposes the running node for use by web pages within the scope of the service worker.
The IPFS node is created when the service worker 'activate' event is fired:
const IPFS = self
The service worker listens for 'fetch' events so that it can respond to certain requests:
self
Finally, the IPFS node is exposed for use by web pages/apps. Service workers are permitted to talk to web pages via a messaging API so we can use ipfs-postmsg-proxy
to talk to the IPFS node running in the worker. We create a "proxy server" for this purpose:
const createProxyServer = // Setup a proxy server that talks to our real IPFS node
Application code
The application code is responsible for registering the service worker and talk to the IPFS node that runs in it.
It is important to do feature detect, in order to verify if the client's browser supports service workers, and then the service worker is ready for being registered. Example:
if 'serviceWorker' in navigator navigatorserviceWorker
Once the service worker is registered, it is possible to start communicating with the IPFS node that is running. To do this, we create a "proxy client" which can talk to our "proxy server" over the messaging API:
if 'serviceWorker' in navigator navigatorserviceWorker