Web3.js Execution – Server vs Browser Differences

mistweb3js

I'm a little bit far from web development, so I have one misunderstanding.

As far as a know, node.js code should be run at the server-side, and web3.js is designed to work at the server side (not sure) because it uses directive "require" and connects to local Ethereum node.

But in examples here https://github.com/ethereum/web3.js/tree/master/example, I see javascript integrated into HTML code that should be executed in the browser. Can somebody explain how it works, what interacts with what, which code executed at server-side and which in browser.

Another question from here, if I use Mist it connects to the local node. But if I want to use web3 in the browser (not mist) I have not node for web3.js to interact with. So the question is – how can I use web3 for the browser(not for Mist)?

Best Answer

Web3 is designed to work both server-side and client side. The client side must be a preprocessed JS bundle, because browsers can't handle advanced JavaScript. You can grab a bundle distribution or create one yourself.

Web3 communicates using XMLHTTPRequest when run in a browser. If you do not have your own node to communicate with the situation is grim at the moment. EtherScan.io provides API key based services that also exposes some of Ethereum JSON-RPC bindings. However as far as I know they are not providing native Web3 provider, so you need to call their specific APIs using their client instead of Web3.

Here is an example project of client side Ethereum application that uses Webpack and Babel (ECMAScript 2016) and EtherScan APIs on a web page.


There are now alternatives such as installing the Metamask extension on Chrome or implementing Metamascara on your site so that the user doesn't need a local node to interact with the blockchain.

Related Topic