Hi I'm trying to interact with an Ethereum smart contract from my node js api.

My controller function is as follows:

var web3 = require('web3');

module.exports.getTokenBalance = function(req, res) {
var abi = //long ABI
var MyContract = web3.eth.contract(abi);

  // initiate contract for an address
  var myContractInstance = MyContract.at('...');
  myContractInstance.balanceOf.call('addr', function(err, data) {


I'm using the [email protected] package. When I try to call this API function I get the following error :

"Cannot read property 'contract' of undefined."

Am I missing something stupid?

1 Answer 1


require('web3') returns a class. You need to instantiate it first. Note the capital W:

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// (or some other provider)

// web3.eth.contract should work down here.
  • Ok cool. Another thing is, I'd like to somehow have a Eth node running on a heroku server so I can send transactions there from my api. Is this a sensible thing to do?
    – SwimmingG
    Jan 14, 2018 at 8:36
  • Seems like an unrelated question, so it might be better to ask it as such. But I do want to make sure you're aware of existing public nodes like Infura.
    – user19510
    Jan 14, 2018 at 8:38
  • What a fantastic resource. Thanks I'll take a look into it.
    – SwimmingG
    Jan 14, 2018 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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