A full-stack application for a cake delivery service, including a customer-facing website, admin dashboard, and backend API.
Thought for 1 second```markdown project="Cake Delivery" file="README.md" ...
┌─────────────────┐ ┌─────────────────┐
│ │ │ │
│ Customer UI │ │ Admin UI │
│ (Next.js) │ │ (Next.js) │
│ │ │ │
└────────┬────────┘ └────────┬────────┘
│ │
│ │
│ │
│ ┌─────────────────┴─────┐
│ │ │
└─────► Backend API │
│ (Express.js) │
│ │
└───────────┬───────────┘
│
│
┌─────┴─────┐
│ │
│ MongoDB │
│ │
└───────────┘
```plaintext
- **Frontend Applications**: Separate Next.js applications for customers and administrators
- **Backend API**: Centralized Express.js API with RESTful endpoints
- **Database**: MongoDB for data persistence
- **Authentication**: JWT-based authentication for secure access
## Backend API
### Backend Technologies
The backend is built with the following technologies:
| Technology | Purpose | Description |
|------------|---------|-------------|
| Express.js | Web Framework | Fast, unopinionated, minimalist web framework for Node.js |
| MongoDB | Database | NoSQL document database for storing application data |
| Mongoose | ODM | MongoDB object modeling tool designed to work in an asynchronous environment |
| JWT | Authentication | JSON Web Tokens for secure authentication between client and server |
| bcryptjs | Password Hashing | Library to hash and compare passwords securely |
| express-validator | Validation | Middleware for validating and sanitizing request data |
| multer | File Uploads | Middleware for handling multipart/form-data for file uploads |
| cors | CORS Support | Middleware to enable Cross-Origin Resource Sharing |
| morgan | Logging | HTTP request logger middleware |
| dotenv | Configuration | Module to load environment variables from .env file |
### Backend Directory Structure
backend/ ├── config/ # Configuration files │ ├── auth.config.js # Authentication configuration │ └── db.config.js # Database configuration ├── controllers/ # Request handlers │ ├── auth.controller.js │ ├── cake.controller.js │ ├── category.controller.js │ ├── order.controller.js │ └── user.controller.js ├── middleware/ # Custom middleware │ ├── auth.middleware.js # Authentication middleware │ └── upload.middleware.js # File upload middleware ├── models/ # Database models │ ├── cake.model.js │ ├── category.model.js │ ├── order.model.js │ └── user.model.js ├── routes/ # API routes │ ├── auth.routes.js │ ├── cake.routes.js │ ├── category.routes.js │ ├── order.routes.js │ └── user.routes.js ├── scripts/ # Utility scripts │ └── seed.js # Database seeding script ├── uploads/ # Uploaded files storage ├── utils/ # Utility functions │ └── helpers.js ├── .env # Environment variables ├── .env.example # Example environment variables ├── package.json # Project dependencies └── server.js # Entry point
### API Endpoints
The backend provides the following RESTful API endpoints:
#### Authentication
- `POST /api/auth/register` - Register a new user
- `POST /api/auth/login` - Authenticate user & get token
- `GET /api/auth/me` - Get current user profile
#### Cakes
- `GET /api/cakes` - Get all cakes (with filtering, sorting, pagination)
- `GET /api/cakes/featured` - Get featured cakes
- `GET /api/cakes/:id` - Get cake by ID
- `POST /api/cakes` - Create a new cake (admin only)
- `PUT /api/cakes/:id` - Update a cake (admin only)
- `DELETE /api/cakes/:id` - Delete a cake (admin only)
#### Categories
- `GET /api/categories` - Get all categories
- `GET /api/categories/:id` - Get category by ID
- `POST /api/categories` - Create a new category (admin only)
- `PUT /api/categories/:id` - Update a category (admin only)
- `DELETE /api/categories/:id` - Delete a category (admin only)
#### Orders
- `GET /api/orders` - Get all orders (admin only)
- `GET /api/orders/user` - Get user orders
- `GET /api/orders/:id` - Get order by ID
- `POST /api/orders` - Create a new order
- `PUT /api/orders/:id` - Update order status (admin only)
- `PUT /api/orders/:id/cancel` - Cancel an order
#### Users
- `GET /api/users` - Get all users (admin only)
- `GET /api/users/:id` - Get user by ID (admin only)
- `PUT /api/users/profile` - Update user profile
- `PUT /api/users/:id/role` - Update user role (admin only)
- `DELETE /api/users/:id` - Delete user (admin only)
### Data Models
The application uses the following data models:
#### User Model
```javascript
{
name: String,
email: String,
password: String,
role: String, // "user" or "admin"
address: {
street: String,
city: String,
state: String,
zipCode: String,
country: String
},
phone: String,
createdAt: Date
}
{
name: String,
description: String,
price: Number,
image: String,
category: ObjectId, // Reference to Category
ingredients: [String],
featured: Boolean,
inStock: Boolean,
createdBy: ObjectId, // Reference to User
createdAt: Date
}{
name: String,
description: String,
image: String,
createdAt: Date
}{
user: ObjectId, // Reference to User
items: [
{
cake: ObjectId, // Reference to Cake
quantity: Number,
price: Number
}
],
totalAmount: Number,
shippingAddress: {
street: String,
city: String,
state: String,
zipCode: String,
country: String
},
paymentMethod: String, // "credit_card", "paypal", "cash_on_delivery"
paymentStatus: String, // "pending", "paid", "failed"
status: String, // "pending", "processing", "shipped", "delivered", "cancelled"
deliveryLocation: {
latitude: Number,
longitude: Number
},
notes: String,
createdAt: Date
}The backend implements JWT-based authentication:
- Registration: Users register with name, email, and password
- Password Security: Passwords are hashed using bcrypt before storage
- Login: Users receive a JWT token upon successful authentication
- Authorization: Middleware verifies JWT tokens and user roles for protected routes
- Admin Access: Special routes are protected with admin-only middleware
The admin dashboard is built with the following technologies:
| Technology | Purpose | Description |
|---|---|---|
| Next.js | Framework | React framework for server-rendered applications |
| React | UI Library | JavaScript library for building user interfaces |
| TypeScript | Language | Typed superset of JavaScript for better development experience |
| Tailwind CSS | Styling | Utility-first CSS framework |
| shadcn/ui | UI Components | High-quality UI components built with Radix UI and Tailwind CSS |
| React Hook Form | Forms | Performant, flexible and extensible forms with easy validation |
| Zod | Validation | TypeScript-first schema validation with static type inference |
| Axios | HTTP Client | Promise-based HTTP client for making API requests |
| Chart.js | Charts | Simple yet flexible JavaScript charting library |
| date-fns | Date Utility | Modern JavaScript date utility library |
| Lucide React | Icons | Beautiful & consistent icons for React |
The admin dashboard provides the following features:
-
Authentication
-
Secure login for administrators
-
JWT-based session management
-
Dashboard
-
Overview of key business metrics
-
Revenue charts and statistics
-
Recent orders and activities
-
Cake Management
-
List, create, edit, and delete cakes
-
Upload cake images
-
Manage cake categories
-
Toggle featured status
-
Order Management
-
View all orders with filtering and search
-
Update order status (processing, shipped, delivered, etc.)
-
View order details including customer information
-
Customer Management
-
View customer list with search functionality
-
Access customer details and order history
-
Category Management
-
Create, edit, and delete cake categories
-
Assign categories to cakes
-
Settings
-
Update admin profile information
-
Change password
-
Configure notification preferences
admin-ui/
├── app/ # Next.js app directory
│ ├── cakes/ # Cake management pages
│ ├── categories/ # Category management pages
│ ├── customers/ # Customer management pages
│ ├── login/ # Authentication pages
│ ├── orders/ # Order management pages
│ ├── settings/ # Settings pages
│ ├── globals.css # Global styles
│ ├── layout.tsx # Root layout component
│ └── page.tsx # Dashboard page
├── components/ # Reusable components
│ ├── ui/ # UI components (shadcn/ui)
│ ├── Header.tsx # Header component
│ └── Sidebar.tsx # Sidebar navigation
├── context/ # React context providers
│ └── AuthContext.tsx # Authentication context
├── lib/ # Utility functions
│ └── utils.ts # Helper functions
├── middleware.ts # Next.js middleware for auth protection
├── public/ # Static assets
├── .env.local # Environment variables
└── package.json # Project dependencies
The admin dashboard implements a secure authentication flow:
- Login Page: Administrators enter credentials
- Authentication: Credentials are verified against the backend API
- Session Management: JWT token is stored in localStorage
- Route Protection: Middleware prevents access to protected routes without authentication
- Auto-logout: Session expires after token expiration
The dashboard provides business insights through:
- Key Metrics: Total revenue, orders, customers, and products
- Charts: Revenue trends over time
- Recent Activity: Latest orders and customer registrations
All data management interfaces follow a consistent pattern:
- List View: Paginated, searchable, and filterable table of items
- Detail View: Comprehensive view of a single item
- Create/Edit Forms: Validated forms for data entry
- Delete Confirmation: Confirmation dialogs for destructive actions
The customer website is built with the following technologies:
| Technology | Purpose | Description |
|---|---|---|
| Next.js | Framework | React framework for server-rendered applications |
| React | UI Library | JavaScript library for building user interfaces |
| TypeScript | Language | Typed superset of JavaScript for better development experience |
| Tailwind CSS | Styling | Utility-first CSS framework |
| shadcn/ui | UI Components | High-quality UI components built with Radix UI and Tailwind CSS |
| React Slick | Carousel | Carousel component for React |
| React Hot Toast | Notifications | Smoking hot React notifications |
| Geolocation API | Location | Browser API for getting user's location for delivery |
The customer website provides the following features:
-
Product Browsing
-
Browse cakes by category
-
View featured cakes
-
Search for specific cakes
-
User Authentication
-
Register new account
-
Login to existing account
-
View and update profile
-
Shopping Cart
-
Add cakes to cart
-
Adjust quantities
-
Remove items
-
View cart summary
-
Checkout Process
-
Enter shipping information
-
Choose payment method
-
Place order
-
Share location for delivery
-
Order Management
-
View order history
-
Check order status
-
Cancel orders (if eligible)
app/
├── app/ # Next.js app directory
│ ├── cart/ # Shopping cart page
│ ├── checkout/ # Checkout process
│ ├── login/ # User login page
│ ├── order/ # Order cakes page
│ ├── profile/ # User profile page
│ ├── signup/ # User registration page
│ ├── globals.css # Global styles
│ ├── layout.tsx # Root layout component
│ └── page.tsx # Homepage
├── components/ # Reusable components
│ ├── ui/ # UI components (shadcn/ui)
│ ├── Footer.tsx # Footer component
│ └── Header.tsx # Header component
├── context/ # React context providers
│ ├── AuthContext.tsx # Authentication context
│ └── CartContext.tsx # Shopping cart context
├── hooks/ # Custom React hooks
│ └── useGeolocation.ts # Geolocation hook
├── public/ # Static assets
├── .env.local # Environment variables
└── package.json # Project dependencies
The shopping cart is implemented using React Context:
- Cart Context: Provides cart state and methods to all components
- Add to Cart: Adds items to cart with quantity
- Update Quantity: Increases or decreases item quantity
- Remove Items: Removes items from cart
- Persistence: Cart is persisted in localStorage
The checkout process follows these steps:
- Cart Review: User reviews items in cart
- Authentication: User must be logged in to proceed
- Shipping Information: User enters or selects delivery address
- Location Sharing: Optional geolocation for precise delivery
- Payment Method: User selects payment method
- Order Confirmation: Order is submitted to the backend
- Confirmation: User receives order confirmation
The customer website is fully responsive:
- Mobile-First: Designed for mobile devices first
- Adaptive Layout: Adjusts layout based on screen size
- Touch-Friendly: Large touch targets for mobile users
- Performance Optimized: Fast loading on all devices
- Node.js (v14 or higher)
- MongoDB (local or Atlas)
- npm or yarn
# Navigate to backend directory
cd backend
# Install dependencies
npm install
# Create .env file (copy from .env.example)
cp .env.example .env
# Seed the database with initial data
npm run seed
# Start the development server
npm run dev
# Navigate to admin-ui directory
cd admin-ui
# Install dependencies
npm install
# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api" > .env.local
# Start the development server
npm run dev
# Navigate to app directory
cd app
# Install dependencies
npm install
# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api" > .env.local
# Start the development server
npm run dev
PORT=5000
NODE_ENV=development
MONGODB_URI=mongodb://localhost:27017/cake-delivery
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRES_IN=1d
CORS_ORIGIN=http://localhost:3000,http://localhost:3001
UPLOAD_DIR=uploads
MAX_FILE_SIZE=5242880
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=adminpassword
NEXT_PUBLIC_API_URL=http://localhost:5000/api
NEXT_PUBLIC_API_URL=http://localhost:5000/api
The application can be deployed using various methods:
Use the provided Docker configuration:
# Build and start all services
docker-compose up -d
- Backend: Deploy to a Node.js hosting service (Heroku, DigitalOcean, AWS)
- Frontend Applications: Deploy to Vercel, Netlify, or other static hosting
- Database: Use MongoDB Atlas for production database
The core business logic revolves around the order processing flow:
-
Cart Creation: User adds cakes to their cart (managed in CartContext)
-
Checkout Initiation: User proceeds to checkout
-
Order Creation: Backend creates an order record with status "pending"
-
Payment Processing: Payment is processed (simulated in the current version)
-
Order Fulfillment: Admin updates order status through admin dashboard
-
"processing" - Order is being prepared
-
"shipped" - Order is out for delivery
-
"delivered" - Order has been delivered
-
"cancelled" - Order has been cancelled
-
Notifications: Status updates are reflected in the customer's order history
The authentication system works as follows:
-
Registration:
-
User submits registration form
-
Backend validates data and checks for existing users
-
Password is hashed using bcrypt
-
User record is created in database
-
JWT token is generated and returned
-
Login:
-
User submits login form
-
Backend validates credentials
-
If valid, JWT token is generated and returned
-
Token contains user ID and role information
-
Authorization:
-
Protected routes check for valid JWT token
-
Admin routes additionally check for admin role
-
Tokens expire after the configured time period
The application follows a clear data flow pattern:
- API Requests: Frontend components make requests to the backend API
- Controller Logic: API controllers handle requests and apply business logic
- Database Operations: Mongoose models interact with MongoDB
- Response Handling: API responses are processed by frontend components
- State Management: React contexts manage application state
- UI Updates: Components re-render based on state changes
Potential future enhancements for the application:
- Payment Integration: Integrate with Stripe or PayPal for real payments
- Real-time Delivery Tracking: Implement real-time tracking with WebSockets
- Reviews & Ratings: Allow customers to review and rate cakes
- Loyalty Program: Implement a points-based loyalty system
- Email Notifications: Send order confirmations and status updates via email
- Advanced Analytics: Enhance admin dashboard with more detailed analytics
- Mobile Applications: Develop native mobile apps for customers and delivery personnel
- Multi-language Support: Add internationalization for multiple languages
- Subscription Service: Implement recurring cake delivery subscriptions
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
This comprehensive README provides a detailed explanation of your cake delivery project, covering all aspects from the system architecture to specific implementation details. It explains the technologies used, the directory structure, key components, and the main application logic in a step-by-step manner.
The document is structured to be useful for both developers who need to understand the technical details and stakeholders who want to understand the overall functionality and flow of the application.
Would you like me to expand on any particular section or add more details about a specific aspect of the project?
Please make sure to add the following environment variables to your project:
<AddEnvironmentVariables names={["PORT", "MONGODB_URI", "JWT_SECRET", "NEXT_PUBLIC_API_URL"]} />
/// Thought for 1 secondGreat! Now that you've added the ADMIN_PASSWORD and ADMIN_EMAIL environment variables to your Vercel project, you're ready to deploy your cake delivery application. Let me guide you through the deployment process and provide some final recommendations.
Since Vercel is primarily designed for frontend applications, you have a few options for deploying your Express backend:
-
Deploy to Vercel Serverless Functions:
-
Convert your Express app to use serverless functions
-
Create a
vercel.jsonconfiguration file in your backend directory:
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "server.js"
}
]
}-
Alternative Backend Hosting:
-
Deploy your Express backend to a service like:
-
Deploy to Vercel:
-
Push your code to a Git repository (GitHub, GitLab, or Bitbucket)
-
Import your repository in the Vercel dashboard
-
Configure the build settings:
-
For the customer website: Set the root directory to
app -
For the admin UI: Set the root directory to
admin-ui -
Environment Variables:
-
Add the following environment variables to your Vercel project for each frontend:
-
NEXT_PUBLIC_API_URL: The URL of your deployed backend API
For MongoDB, you have several options:
-
MongoDB Atlas (Recommended for production):
-
Create a free cluster at MongoDB Atlas
-
Configure network access to allow connections from your backend
-
Add the connection string to your backend's environment variables
-
Alternative MongoDB Hosting:
Before going live, ensure you've completed these steps:
-
Security:
-
Enable HTTPS for all services
-
Set up CORS properly to only allow your frontend domains
-
Implement rate limiting for API endpoints
-
Add security headers (Content-Security-Policy, X-XSS-Protection, etc.)
-
Performance:
-
Enable compression middleware in Express
-
Implement caching for frequently accessed data
-
Optimize images and assets
-
Monitoring:
-
Set up error tracking with a service like Sentry
-
Implement application monitoring
-
Configure alerts for critical errors
-
Backup:
-
Set up automated database backups
-
Implement a disaster recovery plan
-
Testing:
-
Perform thorough testing of all features
-
Test payment processing if implemented
-
Verify mobile responsiveness
Once all components are deployed:
- Update the
NEXT_PUBLIC_API_URLin both frontend applications to point to your deployed backend - Update the
CORS_ORIGINin your backend to allow requests from your frontend domains - Run the database seed script to initialize your database with sample data
- Test the complete flow from the customer website to the admin dashboard
As your application grows, consider these enhancements:
-
Payment Integration:
-
Integrate with Stripe or PayPal for real payments
-
Implement order confirmation emails
-
Delivery Tracking:
-
Add real-time delivery tracking with Google Maps
-
Implement SMS notifications for order updates
-
Analytics:
-
Add Google Analytics or a similar service
-
Implement sales and customer analytics in the admin dashboard
-
Marketing:
-
Add a newsletter subscription feature
-
Implement promotional codes and discounts
Your cake delivery application is now production-ready with a robust backend API, an intuitive admin dashboard, and a user-friendly customer website. The architecture is scalable and can be extended with additional features as your business grows.
Please make sure to add the following environment variables to your project:
Environment Variables Not Added