MERNFull-StackReactNode.jsMongoDB
Building a Full-Stack MERN Application from Scratch
8 min read
Building a Full-Stack MERN Application from Scratch
In this post, I'll walk you through building a complete MERN (MongoDB, Express, React, Node.js) application.
Project Structure
mern-app/
├── client/ # React frontend
│ ├── src/
│ │ ├── components/
│ │ ├── pages/
│ │ ├── hooks/
│ │ └── utils/
│ └── package.json
├── server/ # Node.js/Express backend
│ ├── controllers/
│ ├── models/
│ ├── routes/
│ ├── middleware/
│ └── package.json
└── package.json # Root package.json for scripts
Backend Setup
1. Initialize and Install Dependencies
mkdir server && cd server
npm init -y
npm install express mongoose cors dotenv jsonwebtoken bcryptjs
npm install -D nodemon typescript @types/node @types/express
2. Database Connection
// server/config/db.ts
import mongoose from 'mongoose'
export const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI!)
console.log('MongoDB connected')
} catch (error) {
console.error('DB connection error:', error)
process.exit(1)
}
}
Frontend Setup
1. Create React App with Vite
npm create vite@latest client -- --template react-ts
cd client
npm install
npm install axios react-router-dom @tanstack/react-query
Key Features to Implement
- Authentication: JWT-based auth with refresh tokens
- Protected Routes: Role-based access control
- Error Handling: Centralized error handling middleware
- Validation: Input validation with Zod or Joi
- Testing: Unit tests with Jest, integration tests with Supertest
Deployment
- Frontend: Vercel or Netlify
- Backend: Railway, Render, or AWS
- Database: MongoDB Atlas
- Environment Variables: Configure in platform dashboards
This architecture scales well and follows industry best practices.