2

I got a problem. I am using code below to connect to the eth from node.js app. Everything works perfect as long as I have installed MetaMask in my browser. I can be logged in, logged out, all good when I fetch the data. Problems comes when I uninstall MetaMask. It writes, that currentProvider is undefined. Is there a workaroud? What am I doing wrong?

System: Windows '' Browsers: Brave, Chrome, Opera (havent tried others) Node version: 8.12. web3 version: 1.0.0-beta.46

import Web3 from 'web3';

var web3;

if (typeof window !== 'undefined' && window.web3 !== 'undefined') { 
    web3 = new Web3(window.web3.currentProvider); 
} else { 
    const provider = new   Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/...' );
    web3 = new Web3(provider); 
} 
export default web3;
0

Anyway. I use next.js so the page is initially rendered at the server side. I fetch there, using infura, all the necessary info which works perfectly. The page is shown properly for a second. Then nextjs renders the page again at client side which causes the problem coz window is defined but window.web3 is not. I solved this simply by

import Web3 from 'web3';

    var web3;

    if (typeof window !== 'undefined') {
        if(window.web3 !== 'undefined'){
            const provider = new Web3.providers.HttpProvider(
                'https://rinkeby.infura.io/v3/...'
                );
            web3 = new Web3(provider);
        } else{
            web3 = new Web3(window.web3.currentProvider);
        }
    } else {
        const provider = new Web3.providers.HttpProvider(
            'https://rinkeby.infura.io/v3/...'
            );
        web3 = new Web3(provider);
    }

    export default web3;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.