How to use Web3.js with Nuxt.js

A clean way of accessing the web3 object inside of your components as a nuxt plugin - without storing it in the global window object.

Here's you can use web3.js in Nuxt.js as a plugin:

plugins/web3.js

import Web3 from 'web3'

export default (ctx, inject) => {
    if(!process.client) return // don't run on serverside
    inject( // Inject the $web3 instance into the context object in Nuxt
        'web3',
        window.ethereum ? new Web3(window.ethereum) : null
    )
}

nuxt.config.js

{
    plugins: [
        '@/plugins/web3' // Register the plugin in your nuxt config
    ],
}

Now, you will be able to access the web3 object in your components:

export default {
    mounted(){
        console.log(this.$web3) // If no ethereum provider was injected into the window (like MetaMask does) than the $web3 object will be null
    }
}

Hope that helps.