Tutorials Web3

How to Build a Decentralized Marketplace with MERN Stack and Ethereum Smart Contracts

The rise of Web3 technologies has transformed how digital marketplaces operate. Traditional marketplaces rely on centralized authorities to process payments, manage transactions, and resolve disputes. While effective, these platforms introduce additional fees, security risks, and dependency on intermediaries.
How to Build a Decentralized Marketplace with MERN Stack and Ethereum Smart Contracts

At RAmonka Studio, we help startups and enterprises build decentralized applications that leverage blockchain technology to create secure, transparent, and trustless ecosystems. In this tutorial, we will demonstrate how to build a decentralized marketplace using the MERN stack (MongoDB, Express.js, React.js, and Node.js) integrated with Ethereum smart contracts written in Solidity.

This architecture combines the scalability and user-friendly experience of modern web applications with the security and transparency of blockchain technology. The result is a marketplace where users can list products, purchase items using cryptocurrency, and rely on a smart contract escrow system to guarantee fair transactions. Escrow contracts lock buyer funds until delivery conditions are met, creating trustless commerce between buyers and sellers.

Project Overview

The decentralized marketplace will include:

  • User registration and authentication
  • Wallet connection via MetaMask
  • Product listing management
  • Product search and filtering
  • Ethereum-based escrow payments
  • Smart contract event tracking
  • Transaction history
  • Seller and buyer dashboards
  • Admin analytics panel

Technology Stack

Frontend

  • React.js
  • Redux Toolkit
  • Ethers.js
  • Tailwind CSS

Backend

  • Node.js
  • Express.js
  • MongoDB
  • JWT Authentication

Blockchain

  • Solidity
  • Hardhat
  • OpenZeppelin Contracts
  • Ethereum Network
  • MetaMask

System Architecture

The application consists of three major layers.

Frontend Layer

The React application handles:

  • User interface
  • Wallet integration
  • Product browsing
  • Marketplace actions
  • Blockchain transaction confirmations

Backend Layer

The MERN backend manages:

  • User accounts
  • Product metadata
  • Images
  • Search indexing
  • Notifications
  • Analytics

Blockchain Layer

Smart contracts manage:

  • Escrow payments
  • Ownership verification
  • Transaction settlement
  • Dispute logic
  • Marketplace fees

The blockchain layer becomes the trust engine of the entire platform because funds are stored in escrow until predefined conditions are satisfied.

Step 1: Initialize the MERN Project

Create separate directories for frontend and backend.

mkdir marketplace
cd marketplace

mkdir client
mkdir server

Initialize the backend:

cd server

npm init -y

npm install express mongoose cors dotenv bcryptjs jsonwebtoken

Create the React frontend:

cd ../client

npx create-react-app .

Install blockchain dependencies:

npm install ethers web3modal

Step 2: Design MongoDB Models

While blockchain stores transaction data, marketplace content remains off-chain for efficiency.

User Schema

const UserSchema = new mongoose.Schema({
  username: String,
  email: String,
  walletAddress: String,
  role: String
});

Product Schema

const ProductSchema = new mongoose.Schema({
  title: String,
  description: String,
  price: Number,
  image: String,
  seller: String,
  status: String
});

Statuses can include:

  • Active
  • Pending
  • Delivered
  • Completed
  • Disputed

This mirrors common decentralized marketplace workflows where products move through multiple transaction states.

Step 3: Build Authentication

The platform should support two authentication methods:

Traditional Login

JWT-based authentication:

jwt.sign(
  { userId: user._id },
  process.env.JWT_SECRET
);

Wallet Authentication

Request a signed message from MetaMask:

const signer = provider.getSigner();

const signature =
await signer.signMessage(
  "Verify Wallet Ownership"
);

Store wallet addresses inside MongoDB.

This approach combines Web2 usability with Web3 ownership.

Step 4: Create Product Management APIs

Example product creation endpoint:

router.post('/products', async (req, res) => {

 const product =
 await Product.create(req.body);

 res.json(product);

});

Additional endpoints:

GET /products
GET /products/:id
PUT /products/:id
DELETE /products/:id

These APIs handle marketplace inventory while financial logic remains on-chain.

Step 5: Develop the Escrow Smart Contract

The escrow contract is the core innovation of the marketplace.

Instead of paying sellers directly, buyers deposit funds into the contract. Funds remain locked until the product is received and confirmed.

Escrow Workflow

  1. Seller lists item.
  2. Buyer purchases item.
  3. ETH is sent to escrow.
  4. Seller ships item.
  5. Buyer confirms receipt.
  6. Smart contract releases funds.

Solidity Contract Structure

pragma solidity ^0.8.20;

contract MarketplaceEscrow {

    enum Status {
        Available,
        Purchased,
        Delivered,
        Completed
    }

    struct Order {
        uint id;
        address payable seller;
        address payable buyer;
        uint price;
        Status status;
    }

    mapping(uint => Order) public orders;
}

The contract acts as an autonomous mediator between participants.

Step 6: Prevent Security Vulnerabilities

Smart contracts handling payments must follow strict security practices.

One of the most important protections is preventing reentrancy attacks through the Checks-Effects-Interactions pattern and OpenZeppelin’s ReentrancyGuard.

import
"@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract MarketplaceEscrow
is ReentrancyGuard
{
}

Additional security measures:

  • Access modifiers
  • Ownership verification
  • Emergency pause functions
  • Event logging
  • Input validation

Never deploy escrow contracts without comprehensive testing.

Step 7: Add Marketplace Listing Fees

Most marketplaces generate revenue through listing or transaction fees.

Example:

uint256 public fee = 0.01 ether;

Upon successful sale:

payable(owner).transfer(fee);

Listing fees create sustainable revenue streams while maintaining decentralization.

Step 8: Deploy Using Hardhat

Install Hardhat:

npm install --save-dev hardhat

Initialize:

npx hardhat

Compile:

npx hardhat compile

Deploy:

npx hardhat run scripts/deploy.js

Hardhat remains one of the most widely adopted development environments for Ethereum smart contract deployment and testing.

Step 9: Connect React to Ethereum

Install Ethers.js:

npm install ethers

Initialize provider:

const provider =
new ethers.BrowserProvider(
window.ethereum
);

Request wallet access:

await provider.send(
"eth_requestAccounts",
[]
);

Create contract instance:

const contract =
new ethers.Contract(
contractAddress,
abi,
signer
);

Users can now interact with the blockchain directly from the frontend.

Step 10: Purchase Products Through Escrow

Frontend purchase function:

const tx =
await contract.purchaseProduct(
productId,
{
 value: ethers.parseEther("0.5")
}
);

await tx.wait();

The smart contract stores the payment securely until completion.

This mechanism eliminates the need for centralized payment processors and reduces counterparty risk.

Step 11: Monitor Smart Contract Events

Events allow the frontend to update automatically.

event ProductPurchased(
uint productId,
address buyer
);

React listener:

contract.on(
"ProductPurchased",
(data) => {
 console.log(data);
});

Useful events:

  • ProductListed
  • ProductPurchased
  • ProductDelivered
  • FundsReleased
  • RefundIssued

Event-driven architecture significantly improves user experience.

Step 12: Build Buyer Dashboard

Features include:

  • Active orders
  • Escrow status
  • Delivery tracking
  • Dispute management
  • Purchase history

Dashboard queries MongoDB and blockchain data simultaneously.

Step 13: Build Seller Dashboard

Sellers require:

  • Product management
  • Revenue tracking
  • Active shipments
  • Escrow notifications
  • Wallet earnings

Combining blockchain events with backend analytics creates a professional merchant experience.

Step 14: Implement Dispute Resolution

Advanced marketplaces often include dispute handling.

Example workflow:

  1. Buyer opens dispute.
  2. Funds remain frozen.
  3. Arbitrator reviews evidence.
  4. Smart contract executes final decision.

Many production-grade escrow platforms incorporate dispute mechanisms because real-world commerce occasionally requires mediation.

Step 15: Optimize User Experience

A successful decentralized marketplace should feel as seamless as a traditional eCommerce platform.

Recommended improvements:

ENS Support

Display:

john.eth

instead of wallet addresses.

Transaction Notifications

Show:

Transaction Submitted
Transaction Confirmed
Funds Released

Gas Estimation

Provide estimated costs before execution.

Mobile Wallet Support

Integrate:

  • MetaMask Mobile
  • WalletConnect
  • Coinbase Wallet

Step 16: Testing Strategy

Testing should include:

Smart Contract Tests

npx hardhat test

Validate:

  • Escrow deposits
  • Fund releases
  • Refunds
  • Access control

Backend Tests

npm test

Validate:

  • APIs
  • Authentication
  • Product management

Frontend Tests

Validate:

  • Wallet connectivity
  • Transaction flow
  • State updates

Comprehensive testing is essential for applications that manage financial transactions.

Step 17: Production Deployment

Recommended infrastructure:

Frontend

  • Vercel
  • Netlify

Backend

  • AWS
  • DigitalOcean
  • Render

Database

  • MongoDB Atlas

Blockchain

  • Ethereum Mainnet
  • Polygon
  • Arbitrum

Polygon and Layer-2 networks are often preferred because they reduce transaction costs while maintaining EVM compatibility.

Future Enhancements

A modern Web3 marketplace can evolve with:

NFT Marketplace Module

Allow users to trade ERC-721 assets.

Reputation System

Store seller scores on-chain.

DAO Governance

Enable community voting.

Multi-Currency Payments

Support:

  • ETH
  • USDC
  • DAI
  • Wrapped tokens

AI Fraud Detection

Analyze suspicious transaction patterns.

Conclusion

Building a decentralized marketplace with the MERN stack and Ethereum combines the strengths of traditional web development with blockchain-powered trust. The MERN stack delivers scalability, flexibility, and rapid development, while Solidity smart contracts provide secure escrow transactions and transparent business logic.

By integrating React, Node.js, MongoDB, Ethereum, Hardhat, and Ethers.js, developers can create marketplaces where users retain control of their funds and transactions are executed without relying on centralized intermediaries. Escrow smart contracts become the foundation of trust, ensuring that buyers and sellers can transact securely in a truly decentralized environment.

At RAmonka Studio, we specialize in designing and developing custom blockchain solutions, decentralized applications, Web3 marketplaces, and smart contract ecosystems. Whether you’re launching a startup MVP or building an enterprise-grade marketplace, our team can help transform your concept into a scalable, production-ready Web3 platform.

Leave a Reply

Your email address will not be published. Required fields are marked *