Skip to main content
The Crypto Shop Backend is built on a modern Node.js stack designed for secure cryptocurrency payment processing and e-commerce operations.

Tech Stack Overview

The application leverages the following core technologies:
  • Express.js - RESTful API framework
  • MongoDB - NoSQL database with Mongoose ODM
  • TronWeb - Blockchain integration for TRX payments
  • Socket.io - Real-time transaction notifications
  • JWT - Stateless authentication with HttpOnly cookies

Architecture Diagram

Server Initialization

The application bootstraps in a specific sequence to ensure all services are properly connected:
// src/index.js
import { createServer } from "http";
import { connectDB } from "./config/database.js";
import { startTransactionListener } from "./services/transactionListener.js";
import { initializeSocket } from "./config/socket.js";

// 1. Connect to MongoDB
connectDB();

// 2. Create HTTP server
const server = createServer(app);

// 3. Initialize Socket.io
initializeSocket(server);

// 4. Start blockchain listener
startTransactionListener();

// 5. Start listening for requests
server.listen(PORT);
Reference: src/index.js:1-22

Middleware Stack

The Express application uses a layered middleware approach for security, parsing, and request handling:

Security Middleware

// src/api/index.js
import helmet from "helmet";
import hpp from "hpp";
import rateLimit from "express-rate-limit";

// Helmet: Security headers
app.use(helmet());

// HPP: Prevent HTTP parameter pollution
app.use(hpp());

// Rate limiting: 100 requests per 15 minutes
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
  message: "Too many requests, please try again later"
});
app.use(limiter);
Reference: src/api/index.js:22-33

CORS Configuration

app.use(cors({
  origin: process.env.CLIENT_URL || "http://localhost:3000",
  credentials: true  // Allow cookies
}));
Reference: src/api/index.js:35-38

Body Parsing & Cookies

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
Reference: src/api/index.js:40-42

API Routes Structure

The API is organized into modular route handlers:
app.use("/api/auth", authRoutes);           // Authentication
app.use("/api/users", userRoutes);          // User management
app.use("/api/wallet", walletRoutes);       // Wallet operations
app.use("/api/products", productRoutes);    // Product catalog
app.use("/api/orders", orderRoutes);        // Order management
app.use("/api/transactions", transactionRoutes);
app.use("/api/sessions", sessionRoutes);
app.use("/api/security", securityRoutes);
app.use("/api/admin", adminRoutes);         // Admin panel
Reference: src/api/index.js:44-52

Transaction Listener Service

The transaction listener is a critical component that monitors pending blockchain transactions:
// src/services/transactionListener.js
const CHECK_INTERVAL = 15000; // 15 seconds
const CONFIRMATIONS_REQUIRED = 21;

export const startTransactionListener = () => {
  syncPendingTransactions();
  setInterval(() => {
    syncPendingTransactions();
  }, CHECK_INTERVAL);
};
Reference: src/services/transactionListener.js:102-107

How It Works

  1. Polling Cycle: Every 15 seconds, queries MongoDB for pending transactions
  2. Blockchain Verification: Checks transaction status on TRON network via TronWeb
  3. Status Update: Updates transaction and order status when confirmed
  4. Inventory Management: Decrements product stock on purchase, restores on refund
  5. Real-time Notification: Emits Socket.io event to connected clients
The listener runs continuously in the background, independent of HTTP requests. This ensures transaction confirmations are processed even when users are offline.

Socket.io Integration

Real-time communication enables instant transaction confirmation notifications:
// src/config/socket.js
export const initializeSocket = (server) => {
  io = new Server(server, {
    cors: {
      origin: [process.env.FRONTEND_URL],
      credentials: true,
      methods: ['GET', 'POST']
    }
  });

  io.on('connection', (socket) => {
    socket.on('join-user', (userId) => {
      socket.join(`user:${userId}`);
    });
  });
};
Reference: src/config/socket.js:5-28

Event Emission

export const emitTransactionConfirmed = (userId, orderId, txHash) => {
  const io = getIO();
  io.to(`user:${userId}`).emit('transaction:confirmed', {
    orderId,
    txHash,
    message: 'Your purchase has been confirmed.',
    timestamp: new Date()
  });
};
Reference: src/config/socket.js:37-45

TronWeb Blockchain Interface

The application communicates with the TRON blockchain through TronWeb:
import pkg from 'tronweb';
const { TronWeb } = pkg;

const tronWeb = new TronWeb({
  fullHost: process.env.TRON_NETWORK
});
Reference: src/services/transactionListener.js:4-14
The TRON_NETWORK environment variable should point to:
  • Mainnet: https://api.trongrid.io
  • Nile Testnet: https://nile.trongrid.io

Database Schema Design

MongoDB stores four primary collections:
  • Users - Account credentials, wallet addresses, roles
  • Products - Catalog items with pricing and inventory
  • Orders - Purchase records linking users and products
  • Transactions - Blockchain transaction tracking
See the Order Lifecycle guide for detailed schema information.

Health Check Endpoint

A simple health check endpoint for monitoring:
app.get("/api/health", (req, res) => {
  res.json({ status: "OK" });
});
Reference: src/api/index.js:61-63

Logging

HTTP request logging via Morgan:
import morgan from "morgan";

app.use(morgan(
  process.env.NODE_ENV === "production" ? "combined" : "dev"
));
Reference: src/api/index.js:24
Production mode uses the combined format (Apache-style), while development uses the concise dev format.

Build docs developers (and LLMs) love