How to Create a JSON-RPC Client for Vue.js

With some help from jayson

Posted by Pedro Resende on 09/07/2018 13:49

Today, I had to implement a JSON-RPC client for the Vue.js project I'm working on. Since there wasn't any library available, I thought it would be a good idea to return to the community with a custom made a library to help others. 

I've started by by installing a very well knowned library called Jayson. This library was an implementation of JSON-RPC for client and server side for node.js, the only thing I had to do was import it to Vue.js.

I've started by creating a new file, with the following:

'use strict';

import jayson from 'jayson/lib/client';

export default {
  install: function(Vue, url = url, ssl = false) {
    let client = jayson.http({
      host: url
    if (ssl) {
      client = jayson.https({
        host: url

    Object.defineProperty(Vue.prototype, '$JaysonRPC', { value: client });

then, to allow it to be used in all the project, I've open my main.js file and imported this new library

import JaysonRPC from 'jayson-rpc-vue';

Vue.use(JaysonRPC, '<URL>', false);

Finally, inside my App.vue file I only have to call it by using

this.$JaysonRPC.request('method_name', payload, (err, response) => {
  if (err) throw err;
  console.log(response.result); // 2

That's it, if any one need this library, it's already available on npm or on github.

Any suggestions of improvement are welcome.

NOTE (12-07-2018): Since jayson library had some limitations (missing credentials), I've decided to create a new one based on fetch.js, it's available on npm or on github.