Subscribe to get access to this video

and the whole library of videos, sample code, and tutorials.

Using Websockets with Web3

Web3 can connect to our Ethereum node using Websockets. Websockets will let us keep a two-way connection open between our browser and our client. This means that our geth node will be able to push real-time updates to our browser.

We’ll use this on our page to instantly draw any pixels that are purchased.

In order to use Websockets with geth, we need to add some parameters to our geth command. They look like the flags we used for rpc only they begin with ws. Here’s the command, which you can copy and paste from the video notes:

./bin/geth --datadir=./datadir --nodiscover --rpc --rpcapi "db,personal,eth,net,web3,debug" --rpccorsdomain='*' --rpcaddr="localhost" --rpcport 8545 --ws --wsapi "db,personal,eth,net,web3,debug" --wsorigins='*' --wsaddr="localhost" --wsport 8546 console

Now in our index.js, let’s connect to geth using the web3 WebsocketProvider:

// src/steps/002-websockets.js

// first we'll require web3
var Web3 = require('web3');

// next we'll create a new instance of web3.
var web3 = new Web3();

// Set the provider
  new Web3.providers.WebsocketProvider(

function checkBalance() {
  web3.eth.personal.getAccounts().then(accounts => {
    console.log('accounts', accounts);

    web3.eth.getBalance(accounts[0]).then(balance => {
      console.log('balance[0]', balance);

And let’s add this checkBalance() function to our document onload.

If we check in our browser console, we can see the account balances there, so it worked. If you didn’t see those balances, double check that you geth running and that the hostname and port match.


Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.