Web3 Tutorial Node.js

Detailed code tutorial for beginners on using Web3.js and Node.js. Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain, while Node.js is a JavaScript runtime environment that enables you to run JavaScript code on the server-side. This tutorial will guide you through the process of setting up a basic project, connecting to the Ethereum network, and performing some common tasks using Web3.js and Node.js.



Set up the project




Create a new directory for your project and navigate to it using the command line:

mkdir web3-node-tutorial cd web3-node-tutorial


Initialize a new Node.js project by running the following command and following the prompts:

npm init


Install the required dependencies: Web3.js and dotenv (to store sensitive information):

npm install web3 dotenv


Create a new file named index.js in the project directory.




Configure the environment



  • Create a new file named .env in the project directory.
  • Open the .env file and add the following lines:


INFURA_PROJECT_ID=your_infura_project_id
PRIVATE_KEY=your_private_key



Replace your_infura_project_id with your Infura project ID, which you can obtain by creating an account at https://infura.io/.
Replace your_private_key with your Ethereum account's private key. Make sure to keep this information secure.


  • Create a new file named config.js in the project directory.
  • Open the config.js file and add the following code:


require('dotenv').config();

module.exports = {
  infuraProjectId: process.env.INFURA_PROJECT_ID,
  privateKey: process.env.PRIVATE_KEY
};





Initialize Web3.js and connect to the Ethereum network


Open the index.js file and add the following code at the beginning of the file:

const Web3=require('web3');
const config=require('./config');

const web3=new Web3(`https://mainnet.infura.io/v3/${config.infuraProjectId}`);



This code imports the necessary modules, initializes a new Web3 instance, and connects to the Ethereum mainnet using the Infura project ID from the configuration file.



Interact with the Ethereum network


Add the following code to the index.js file to perform a simple task, such as getting the latest block number:

async function getLatestBlockNumber() {
  const blockNumber=await web3.eth.getBlockNumber();
  console.log('Latest block number:', blockNumber);
}

getLatestBlockNumber();



This code defines an async function named getLatestBlockNumber that uses the getBlockNumber method of the web3.eth object to retrieve the latest block number from the Ethereum network. The block number is then logged to the console.



Run the code


  1. Save the index.js file.
  2. In the command line, navigate to the project directory and run the following command:


node index.js


If everything is set up correctly, you should see the latest block number printed to the console.


Want to find a web3 job?

Receive emails of Web3 Tutorial Node.js

More by Jonas Bostoen
Ask me anything