How to Build a Blockchain App with Ethereum, Web3.js & Solidity Smart Contracts

·

Creating your first blockchain application might seem daunting, but with the right tools and guidance, you can build a fully functional decentralized app (dApp) using Ethereum, Web3.js, and Solidity. This comprehensive guide walks you through every step—from setting up your development environment to deploying a live marketplace dApp on the Ethereum blockchain.

Whether you're new to blockchain or expanding your developer toolkit, this tutorial delivers hands-on experience building a real-world application that allows users to list and buy digital products using cryptocurrency.


Understanding the Core Concepts

Before diving into code, it's essential to grasp the foundational elements of blockchain technology and how they come together in decentralized applications.

What Are We Going to Build?

You’ll create a blockchain-powered marketplace, similar in concept to Craigslist or eBay—but fully decentralized. This dApp will allow users to:

The entire backend logic runs on the Ethereum blockchain through Solidity smart contracts, while the frontend is built with React.js and connected via Web3.js. No central server is required—the blockchain acts as both database and backend.

This project integrates core blockchain concepts into a practical, working application that simulates real-world use cases.

What Is a Blockchain?

A blockchain is a decentralized, peer-to-peer network of computers (called nodes) that collectively maintain a shared ledger of transactions. Unlike traditional databases hosted on centralized servers, blockchains distribute data across thousands of nodes worldwide.

Key characteristics include:

Think of it as a global, tamper-proof computer where code and data are replicated across all participating machines. In our app, the blockchain will store product listings, ownership records, and transaction history.

👉 Discover how blockchain networks power next-generation applications.

What Is a Smart Contract?

Smart contracts are self-executing programs deployed on the blockchain. Written in Solidity, these contracts define rules and automatically enforce them when conditions are met—like a vending machine that releases an item when payment is received.

In our marketplace:

Once deployed, smart contracts are immutable—meaning their code cannot be changed. This ensures trust and security, as users know the rules won’t be altered after deployment.

How Does a Smart Contract Work?

When a user buys a product:

  1. They send ETH to the smart contract
  2. The contract validates the payment
  3. Ownership is transferred to the buyer
  4. Funds are sent directly to the seller

No intermediaries. No delays. Just automated, trustless execution.


How Does a Blockchain App Work?

Traditional web apps rely on client-server architecture: your browser (client) talks to a backend server, which accesses a centralized database.

A blockchain app flips this model:

This eliminates reliance on central authorities and gives users full control over their assets and identities—typically managed through wallets like MetaMask.


Setting Up Your Development Environment

To build this dApp, you'll need several key tools installed locally.

Install Required Dependencies

1. Ganache – Personal Blockchain

Ganache provides a local Ethereum blockchain for development. It gives you 10 test accounts preloaded with 100 ETH each—perfect for testing without spending real money.

Download and run Ganache Desktop or CLI. Once launched, it starts a local node at http://127.0.0.1:7545.

2. Node.js & npm

Ensure Node.js and npm (Node Package Manager) are installed:

node -v
npm -v

If not installed, download from nodejs.org.

3. Truffle Framework

Truffle simplifies Ethereum development with tools for compiling, testing, and deploying smart contracts.

Install globally:

npm install -g [email protected]

4. MetaMask Wallet

Install the MetaMask browser extension to connect your browser to Ethereum networks.

Configure it to connect to your local Ganache network by adding a custom RPC:

Import test accounts using private keys from Ganache.


Building the Smart Contract

We’ll write our smart contract in Solidity, focusing on product management and ownership transfer.

Step 1: Initialize Project Structure

Use a starter kit to accelerate setup:

git clone https://github.com/dappuniversity/starter_kit marketplace
cd marketplace
npm install

This includes React, Web3.js, Bootstrap, and Truffle preconfigured.

Create the smart contract file:

touch src/contracts/Marketplace.sol

Start with basic structure:

pragma solidity ^0.5.0;

contract Marketplace {
    string public name = "Dapp University Marketplace";
    uint public productCount = 0;
    mapping(uint => Product) public products;

    struct Product {
        uint id;
        string name;
        uint price;
        address payable owner;
        bool purchased;
    }

    event ProductCreated(
        uint id,
        string name,
        uint price,
        address payable owner,
        bool purchased
    );

    constructor() public {
        name = "Dapp University Marketplace";
    }

    function createProduct(string memory _name, uint _price) public {
        require(bytes(_name).length > 0);
        require(_price > 0);
        productCount++;
        products[productCount] = Product(productCount, _name, _price, msg.sender, false);
        emit ProductCreated(productCount, _name, _price, msg.sender, false);
    }
}

Compile and deploy:

truffle compile
truffle migrate

Step 2: Add Purchase Functionality

Extend the contract with a purchaseProduct function:

function purchaseProduct(uint _id) public payable {
    Product memory _product = products[_id];
    address payable _seller = _product.owner;

    require(_product.id > 0 && _product.id <= productCount);
    require(msg.value >= _product.price);
    require(!_product.purchased);
    require(_seller != msg.sender);

    _product.owner = msg.sender;
    _product.purchased = true;
    products[_id] = _product;

    address(_seller).transfer(msg.value);

    emit ProductPurchased(_product.id, _product.name, _product.price, msg.sender, true);
}

Deploy updated contract:

truffle migrate --reset

Building the Frontend with React & Web3.js

Now connect your React app to interact with the smart contract.

Load Web3 and Connect Wallet

In App.js, detect MetaMask and initialize Web3:

async loadWeb3() {
  if (window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    await window.ethereum.enable();
  } else {
    window.alert("Please install MetaMask!");
  }
}

Fetch Blockchain Data

Load account and contract instance:

async loadBlockchainData() {
  const web3 = window.web3;
  const accounts = await web3.eth.getAccounts();
  this.setState({ account: accounts[0] });

  const networkId = await web3.eth.net.getId();
  const networkData = Marketplace.networks[networkId];
  
  if (networkData) {
    const marketplace = new web3.eth.Contract(Marketplace.abi, networkData.address);
    this.setState({ marketplace });

    const productCount = await marketplace.methods.productCount().call();
    this.setState({ productCount });

    for (let i = 1; i <= productCount; i++) {
      const product = await marketplace.methods.products(i).call();
      this.setState({
        products: [...this.state.products, product]
      });
    }
  } else {
    window.alert("Contract not deployed on current network");
  }
}

Enable Product Listing & Purchasing

Create forms in Main.js to call createProduct() and purchaseProduct() via Web3.js.

Use loading states to improve UX during transactions.

👉 See how developers are leveraging blockchain platforms today.


Frequently Asked Questions

Q: Can I modify a smart contract after deployment?
A: No—smart contracts are immutable once deployed. You must deploy a new version if changes are needed.

Q: What is Web3.js used for?
A: Web3.js enables frontend applications to communicate with Ethereum nodes and smart contracts via JavaScript.

Q: Why use Ganache for development?
A: Ganache provides a safe, local environment to test dApps without risking real funds or affecting live networks.

Q: How do users pay for transactions?
A: Users pay gas fees in ETH to execute actions like buying products or listing items.

Q: Is this dApp secure?
A: Yes—the use of require() statements prevents invalid inputs and unauthorized actions. Always test thoroughly before deployment.

Q: Can I deploy this on the main Ethereum network?
A: Absolutely. After testing locally, configure Truffle to deploy on mainnet using Infura or Alchemy.


Final Steps: Deploying Your dApp

Once tested locally:

  1. Connect Truffle to a testnet (e.g., Goerli) or mainnet
  2. Update truffle-config.js with provider credentials
  3. Run truffle migrate --network goerli
  4. Host frontend on IPFS or Netlify

Your dApp is now live and accessible globally.

👉 Explore tools that streamline blockchain deployment workflows.


By following this guide, you've built a complete full-stack blockchain application using Ethereum, Solidity, Web3.js, and React—core technologies driving innovation in decentralized systems.

With hands-on experience in smart contracts, frontend integration, and deployment, you're well-equipped to explore more advanced dApp development opportunities in DeFi, NFTs, or Web3 gaming.

Keep building—and keep learning.