Web3.js Node.js – Fix TypeError: Web3 is not a Constructor When Using Node.js with Truffle-Contract

nodejssoliditytruffletruffle-contractweb3js

I'm trying to use node.js with my smart contract for my app. As I've tried to convert from using the default app.js set-up to index.js set-up I've ran into this weird issue I can't fix.

It throws the error when trying to instantiate my .json file with truffle-contract.

App.contracts.Flip = TruffleContract(FlipArtifact); //at this line it goes to truffle-contract.js and throws this error: 

var BigNumber = (new Web3()).toBigNumber(0).constructor;

TypeError: Web3 is not a constructor   

I had the exact same thing but in my app.js where truffle puts it automatically and it was working fine.

Could someone please explain the difference between using truffle-contract in my app.js/client-side and my index.js/server-side. Thanks for any help.

Best Answer

If you're running in a browser with MetaMask, then Web3 is injected as a side effect of this (although try not to rely on this behaviour). In server-side code, you must import web3 yourself, by putting something like:

const Web3 = require('web3')

near the start of your code. You may also have to npm install web3 or yarn install web3, and if you're using BigNumber (which they no longer bundle with Web3 1.0) then you probably want to specify npm install web3@^0.20.6 or yarn install web3@^0.20.6.

Related Topic