Develop Your First Dapp with Web3.js

·

Introduction to Web3.js

The rise of cryptocurrencies has ushered in a new era of digital payments, made possible by blockchain technology. Decentralized applications (DApps) represent a revolutionary vision for the internet, fundamentally different from today's centralized systems. At the core of DApps lie digital assets like cryptocurrencies, programmable tokens, and smart contracts—all deployed on blockchains.

Web3.js is a library collection enabling interaction with local or remote Ethereum nodes via HTTP or IPC connections. It serves as the backbone for developing decentralized applications by providing JavaScript APIs to communicate with Ethereum clients like Geth.

In this guide, we'll walk through building a DApp using Web3.js.


Getting Started

Prerequisites

To follow this tutorial, ensure you have:


Key Concepts

1. Blockchain

A blockchain is an immutable, auditable database where data can only be appended (not modified/deleted). Blocks of data are chained cryptographically, forming a decentralized ledger.

2. Ethereum

A decentralized platform for executing smart contracts—self-enforcing agreements written in code—without intermediaries.

3. Smart Contracts

Programs stored on the blockchain that run exactly as programmed. Written in languages like Solidity, they enable trustless transactions.

4. Decentralized Applications (DApps)

DApps have three core components:

DApp Properties:

5. Web3.js

A JavaScript library that:

How It Works

Web3.js Architecture
Web3.js bridges frontend apps and the blockchain via JSON-RPC.


Building Your First DApp

Step 1: Environment Setup

  1. Install dependencies:

    npm install -g truffle ganache solc
  2. Initialize a Truffle project:

    mkdir dapp-demo && cd dapp-demo  
    truffle init

Step 2: Smart Contract Development

Create Greeting.sol in contracts/:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Greeting {
    string public greeting = "Hello, Web3!";

    function updateGreeting(string memory _greeting) public {
        greeting = _greeting;
    }

    function getGreeting() public view returns (string memory) {
        return greeting;
    }
}

Step 3: Compile and Deploy

  1. Compile:

    truffle compile
  2. Deploy to Ganache (local blockchain):

    truffle migrate --network development

Step 4: Frontend Integration

  1. Set up a client folder:

    mkdir client && cd client  
    npm init -y && npm install web3 lite-server jquery
  2. Create index.html and src/index.js:

    <!-- index.html -->
    <input id="greetingInput" placeholder="New greeting" />
    <button id="submitGreeting">Update</button>
    <h2 id="currentGreeting"></h2>
    // index.js
    import { getWeb3, getContract } from './utils';
    
    async function initApp() {
        const web3 = await getWeb3();
        const contract = await getContract(web3);
        const accounts = await web3.eth.getAccounts();
    
        // Display current greeting
        const greeting = await contract.methods.getGreeting().call();
        document.getElementById('currentGreeting').innerText = greeting;
    
        // Update greeting
        document.getElementById('submitGreeting').addEventListener('click', async () => {
            const newGreeting = document.getElementById('greetingInput').value;
            await contract.methods.updateGreeting(newGreeting).send({ from: accounts[0] });
            alert('Greeting updated!');
        });
    }
    initApp();

Step 5: Run the DApp

Start the dev server:

lite-server

Access at http://localhost:3000.


FAQs

Q1: What’s the difference between Web3.js and Ethers.js?

A: Both are Ethereum JS libraries, but Ethers.js is newer with a smaller bundle size and clearer API. Web3.js is more established but heavier.

Q2: How do I connect MetaMask to my DApp?

A: Use window.ethereum.enable() to request account access. Modern DApps often use Web3Modal for multi-wallet support.

Q3: Why use Truffle over Hardhat?

A: Truffle offers built-in testing and deployment tools. Hardhat is more modular and faster for advanced developers.


Conclusion

By leveraging Web3.js, you’ve built a functional DApp that interacts with the Ethereum blockchain. Key takeaways:

  1. Smart contracts handle on-chain logic.
  2. Web3.js bridges frontend and blockchain.

👉 Explore advanced DApp development for scaling, gas optimization, and security best practices.

Further Reading: