Skip to main content
This guide walks you through installing and configuring the Crypto Shop Backend from scratch.

Prerequisites

Before installing, ensure your system meets these requirements:

Required Software

Node.js

Version 16 or higherDownload from nodejs.orgVerify installation:
node --version
# Should output v16.0.0 or higher

MongoDB

Version 5.0 or higherInstall locally or use MongoDB AtlasVerify installation:
mongosh --version

npm

Comes with Node.jsVerify installation:
npm --version

Git

For cloning the repositoryVerify installation:
git --version

TRON Network Access

You’ll need access to the TRON blockchain:
The Nile testnet is recommended for development. It provides free testnet TRX and mirrors mainnet functionality.

Installation Steps

1

Clone the Repository

Clone the Crypto Shop Backend repository:
git clone <your-repository-url>
cd crypto-shop-backend
Alternatively, download and extract the ZIP file from your repository.
2

Install Dependencies

Install all required npm packages:
npm install
This installs:
  • Express - Web framework
  • Mongoose - MongoDB ODM
  • TronWeb - TRON blockchain integration
  • Socket.io - Real-time notifications
  • JWT - Authentication tokens
  • bcryptjs - Password hashing
  • And more (see package.json for complete list)
Installation typically takes 1-3 minutes depending on your internet connection.
3

Set Up MongoDB

Choose one of the following options:
Start MongoDB locally:macOS (Homebrew):
brew services start mongodb-community
Linux (systemd):
sudo systemctl start mongod
Windows:
net start MongoDB
Verify it’s running:
mongosh
# Should connect successfully
4

Configure Environment Variables

Create a .env file in the project root:
cp .env.example .env
Edit .env with your configuration:
.env
# MongoDB Connection
MONGODB_URI=mongodb://localhost:27017/crypto-shop
# For Atlas: mongodb+srv://user:[email protected]/crypto-shop

# Server Configuration
NODE_ENV=development
PORT=3000

# TRON Network
# Testnet (development):
TRON_NETWORK=https://nile.trongrid.io
# Mainnet (production):
# TRON_NETWORK=https://api.trongrid.io

# JWT Secrets
# Generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
ACCESS_TOKEN_SECRET=your_access_token_secret_min_32_characters
REFRESH_TOKEN_SECRET=your_refresh_token_secret_min_32_characters

# CORS Configuration
CLIENT_URL=http://localhost:3000

Generate Secure Secrets

Generate cryptographically secure secrets for JWT:
# Generate ACCESS_TOKEN_SECRET
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# Generate REFRESH_TOKEN_SECRET
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Never commit your .env file to version control! It contains sensitive secrets. The .env file is already in .gitignore.
5

Start the Server

Run the development server with auto-reload:
npm run dev
Or start in production mode:
npm start
You should see:
🚀 Server running on port 3000
MongoDB connected successfully
Transaction listener started
6

Verify Installation

Test that everything is working:1. Health Check
curl http://localhost:3000/api/health
Expected: {"status":"OK"}2. API DocumentationOpen in your browser:
http://localhost:3000/api/docs
You should see the Swagger UI interface.3. Database ConnectionCheck server logs for:
MongoDB connected successfully

Configuration Reference

Environment Variables

Complete reference of all supported environment variables:
VariableRequiredDefaultDescription
MONGODB_URIYes-MongoDB connection string
NODE_ENVNodevelopmentEnvironment: development, production
PORTNo3000Server port
TRON_NETWORKYes-TRON RPC endpoint URL
ACCESS_TOKEN_SECRETYes-JWT access token secret (min 32 chars)
REFRESH_TOKEN_SECRETYes-JWT refresh token secret (min 32 chars)
CLIENT_URLYes-Frontend URL for CORS
MERCHANT_WALLET_ADDRESSNo-Fallback merchant wallet (optional)

TRON Network Endpoints

TRON_NETWORK=https://nile.trongrid.io
Always use testnet endpoints for development. Mainnet transactions use real TRX with actual value.

Project Structure

Understand the codebase organization:
crypto-shop-backend/
├── src/
│   ├── api/              # API routes and handlers
│   │   ├── auth/         # Authentication endpoints
│   │   ├── orders/       # Order management
│   │   ├── products/     # Product catalog
│   │   ├── admin/        # Admin dashboard
│   │   ├── transactions/ # Transaction history
│   │   └── index.js      # Main Express app
│   ├── config/           # Configuration files
│   │   ├── database.js   # MongoDB connection
│   │   ├── socket.js     # Socket.io setup
│   │   └── swagger.js    # API documentation
│   ├── middlewares/      # Express middlewares
│   │   └── auth.js       # JWT authentication
│   ├── models/           # Mongoose schemas
│   │   ├── User.js       # User model
│   │   ├── Order.js      # Order model
│   │   ├── Product.js    # Product model
│   │   └── Transaction.js # Transaction model
│   ├── services/         # Business logic
│   │   ├── tron.service.js         # TRON blockchain integration
│   │   └── transactionListener.js  # Payment confirmation
│   ├── utils/            # Helper functions
│   │   └── tokenUtils.js # JWT utilities
│   └── index.js          # Server entry point
├── .env                  # Environment variables (create this)
├── .env.example          # Environment template
├── package.json          # Dependencies
└── README.md            # Project documentation

Database Setup

The application automatically creates collections and indexes on first run. No manual database setup is required.

Collections Created

  • users - User accounts and wallets
  • products - Product catalog
  • orders - Purchase orders
  • transactions - Blockchain transactions
  • sessions - Active user sessions (if implemented)

Initial Admin Account

To create an admin account, manually register a user and update their role in MongoDB:
mongosh crypto-shop
db.users.updateOne(
  { email: "[email protected]" },
  { $set: { role: "admin" } }
)
Alternatively, implement a seed script or use the first registered user as admin.

Security Configuration

The backend includes several security features enabled by default:

Built-in Security

  • Helmet - Sets secure HTTP headers
  • CORS - Configured cross-origin resource sharing
  • Rate Limiting - Prevents abuse (100 requests per 15 minutes)
  • HPP - HTTP Parameter Pollution protection
  • HttpOnly Cookies - Secure token storage
  • bcrypt - Password hashing with salt rounds

Production Checklist

Before deploying to production:
  • Set NODE_ENV=production
  • Use strong, unique JWT secrets (min 32 chars)
  • Enable HTTPS/SSL
  • Configure proper CORS origins
  • Use MongoDB Atlas with IP whitelist
  • Set up monitoring and logging
  • Enable rate limiting (already configured)
  • Use environment-specific TRON endpoints
  • Set secure cookie settings
  • Review and update .env variables

Troubleshooting

Error: MongoServerError: Authentication failedSolutions:
  • Verify MongoDB is running: mongosh
  • Check MONGODB_URI in .env
  • For Atlas: verify IP whitelist and credentials
  • Ensure database user has proper permissions
Error: EADDRINUSE: address already in use :::3000Solutions:
  • Change PORT in .env to a different value
  • Kill the process using port 3000:
    # Find process
    lsof -i :3000
    # Kill it
    kill -9 <PID>
    
Error: Connection to TRON network failedSolutions:
  • Verify TRON_NETWORK URL in .env
  • Test endpoint:
    curl https://nile.trongrid.io/wallet/getnowblock
    
  • Check your internet connection
  • Try alternative endpoints (see Configuration Reference)
Error: JWT secret must be at least 32 charactersSolution: Generate proper secrets:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Update .env with the generated values.
Error: Cannot find module 'express'Solution: Reinstall dependencies:
rm -rf node_modules package-lock.json
npm install

Verify Installation

Run through this checklist to ensure everything is properly installed:
1

Server Health

curl http://localhost:3000/api/health
✓ Should return {"status":"OK"}
2

Database Connection

Check server logs for:
MongoDB connected successfully
3

API Documentation

Visit http://localhost:3000/api/docs✓ Swagger UI should load
4

Transaction Listener

Check server logs for:
Transaction listener started
5

Test Registration

curl -X POST http://localhost:3000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "username": "testuser",
    "password": "password123",
    "passwordConfirm": "password123"
  }'
✓ Should return user data with wallet address

Next Steps

Quickstart Guide

Follow the quickstart to make your first API calls

API Reference

Explore all available endpoints

Authentication

Learn about JWT and role-based access

Deployment

Deploy to production

Build docs developers (and LLMs) love