Search code examples
javascriptvue.jsrpcnuxt.js

How to create plugin for Nuxt.js?


This is my rpc.js plugin file:

const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc')

const protocol = 'http'
const rpcuser = 'root'
const rpcpassword = 'toor'
const host = '127.0.0.1'
const port = '43782'
const rpcHref = `${protocol}://${rpcuser}:${rpcpassword}@${host}:${port}/`
const bitcoinRpc = createBitcoinRpc(rpcHref)

export default ({ app }, inject) => {
  inject('bitcoinRpc', (method) =>
    bitcoinRpc(method).then((result) => console.log('That was easy!', result))
  )
}

This is my nuxt.config.js file:

...
plugins: [{ src: '@/plugins/gun.js' }, { src: '@/plugins/rpc.js' }],
...

If I call this.$bitcoinRpc('getnewaddress') somewhere in the component methods, then I get an error, but if I call this method inside the rpc plugin itself, then everything works as expected:

// plugins/rpc.js:
// Declare constants and inject above
...
bitcoinRpc('getnewaddress').then((result) =>
  console.log('That was easy!', result)
)

I get the expected result in the terminal:

That was easy! 2N8LyZKaZn5womvLKZG2b5wGfXw8URSMptq 14:11:21

Explain what I'm doing wrong?


Solution

  • The method outlined by me was correct.

    The error that occurred was caused by the fact that on the client side it was not possible to use the server side libraries.