A complete Express.js backend for a grocery delivery application with user authentication, product management, order processing, and admin panel.
- User registration and login with JWT authentication
- Browse product catalog with filtering and search
- Shopping cart management
- Order placement and tracking
- Feedback and review system
- Order history
- Admin dashboard with analytics
- User management (activate/deactivate)
- Product CRUD operations
- Order management and status updates
- Feedback management and responses
- MongoDB with Mongoose ODM
- JWT authentication
- Password hashing with bcrypt
- Input validation and sanitization
- Rate limiting and security headers
- CORS enabled for frontend integration
- Comprehensive error handling
- Install dependencies:
yarn install- Set up environment variables:
cp .env.example .env
# Edit .env with your configuration-
Start MongoDB (make sure MongoDB is running on your system)
-
Seed the database with sample data:
node scripts/seedDatabase.js- Start the development server:
yarn devPOST /api/users/register- Register new userPOST /api/users/login- User loginGET /api/users/profile- Get user profilePUT /api/users/profile- Update user profile
GET /api/products- Get all products (with filtering)GET /api/products/:id- Get single productGET /api/products/category/:category- Get products by categoryGET /api/products/search- Search productsPOST /api/products/:id/reviews- Add product review
GET /api/cart- Get user's cartPOST /api/cart/add- Add item to cartPUT /api/cart/update- Update cart item quantityDELETE /api/cart/remove/:productId- Remove item from cart
POST /api/orders- Create new orderGET /api/orders- Get user's ordersGET /api/orders/:id- Get single orderPUT /api/orders/:id/cancel- Cancel orderPOST /api/orders/payment- Process payment
POST /api/feedback- Submit feedbackGET /api/feedback- Get user's feedbackGET /api/feedback/:id- Get single feedbackPUT /api/feedback/:id- Update feedbackDELETE /api/feedback/:id- Delete feedback
GET /api/admin/dashboard- Dashboard statsGET /api/admin/users- Manage usersGET /api/admin/products- Manage productsPOST /api/admin/products- Create productPUT /api/admin/products/:id- Update productDELETE /api/admin/products/:id- Delete productGET /api/admin/orders- Manage ordersPUT /api/admin/orders/:id/status- Update order statusGET /api/admin/feedback- Manage feedbackPOST /api/admin/feedback/:id/respond- Respond to feedback
const registerUser = async (userData) => {
try {
const response = await fetch('http://localhost:5000/api/users/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const data = await response.json();
if (data.success) {
localStorage.setItem('token', data.data.token);
localStorage.setItem('user', JSON.stringify(data.data.user));
}
return data;
} catch (error) {
console.error('Registration error:', error);
}
};const fetchProducts = async (filters = {}) => {
try {
const queryParams = new URLSearchParams(filters);
const response = await fetch(`http://localhost:5000/api/products?${queryParams}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch products error:', error);
}
};const addToCart = async (productId, quantity) => {
try {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:5000/api/cart/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ productId, quantity })
});
const data = await response.json();
return data;
} catch (error) {
console.error('Add to cart error:', error);
}
};const createOrder = async (orderData) => {
try {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:5000/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(orderData)
});
const data = await response.json();
return data;
} catch (error) {
console.error('Create order error:', error);
}
};After seeding the database:
Admin:
- Email: admin@snapit.com
- Password: admin123
Sample User:
- Email: user@example.com
- Password: user123
├── controllers/ # Route handlers
├── middleware/ # Custom middleware
├── models/ # Mongoose schemas
├── routes/ # API routes
├── scripts/ # Utility scripts
├── .env # Environment variables
├── server.js # Main server file
└── README.md
Required environment variables in .env:
MONGODB_URI=mongodb://localhost:27017/grocery-store
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d
PORT=5000
NODE_ENV=development
FRONTEND_URL=http://localhost:5173
ADMIN_EMAIL=admin@snapit.com
ADMIN_PASSWORD=admin123
PAYMENT_SUCCESS_RATE=0.8
# Start development server
yarn dev
# Seed database
node scripts/seedDatabase.js
# Start production server
yarn start- JWT authentication
- Password hashing with bcrypt
- Rate limiting
- Input validation and sanitization
- CORS configuration
- Security headers with Helmet
- Error handling middleware
- Set up the backend server and database
- Test API endpoints with Postman or similar tool
- Integrate with your React frontend
- Add file upload for product images
- Implement email notifications
- Add payment gateway integration
- Deploy to production