api-mount

Library for making communication between front-end and back-end simple

Usage no npm install needed!

<script type="module">
  import apiMount from 'https://cdn.skypack.dev/api-mount';
</script>

README

api-mount

by Vytenis Urbonavičius

api-mount provides a straightforward way for connecting Node.js based server with either browser or Node.js client.

Once setup, it makes it feel as if client is calling server-side API methods directly. HTTP requests are abstracted away.

Both Client and Server

api-mount has separate entry points for Node.js and browser environments. This prevents such situations as when Node.js logic ends up in the bundle meant for browser.

If, for some reason, you would want to explicitly install server-only or client-only package without the other part - you can do so. api-mount is actually fused out of 2 smaller packages which can be used independently:

  • api-mount-server - allows exposing API using api-mount protocol. Package contains detailed README about how APIs can be defined, exposed, how server can be configured, how protocol looks like, etc.
  • api-mount-client - allows mounting API which was previously exposed by api-mount-server. Package contains detailed README about how APIs can be consumed.

Using above packages directly have little benefit apart from saving few kilobytes of disk space on a development machine - build size should not be impacted.

Installation

npm install --save api-mount

Usage Example

If you are not yet an experienced JS/TS developer, you might find "Try it out" section of api-mount-client documentation useful.

api-mount when used in Node.js environment contains exact methods of both api-mount-server and api-mount-client. Please see detailed documentation by clicking on these package names.

Below code serves only as an example:

import {apiMountFactory, mountApi} from 'api-mount'

const serverApi = {
  test: () => 'hello',
}

// Serving API on localhost:3000
const ApiMount = apiMountFactory()
ApiMount.exposeApi(serverApi)

// Mounting API which has just been served above
const clientApi = mountApi({baseUrl: 'http://localhost:3000'})
await clientApi.test() // 'hello'

Notice that in the above example apiMountFactory comes from api-mount-server while mountApi comes from api-mount-client.