A Next.js-based backend API for Money Mitra, a financial management platform that provides AI-powered financial advice, user authentication, and personalized financial tracking.
Money Mitra Backend is a RESTful API built with Next.js App Router that serves as the core backend infrastructure for the Money Mitra financial management application. The platform combines secure user authentication with AI-powered financial advisory capabilities using Google's Gemini AI.
-
User Authentication System
- JWT-based session management
- Secure password hashing with bcrypt
- Sign up, sign in, and sign out endpoints
- HTTP-only cookie authentication
-
User Management
- Role-based access control (student, teacher, admin)
- User profiles with financial tracking metrics (points, rank, accuracy)
- Subscription plans (free, pro)
- Two-factor authentication support
-
AI Financial Advisor
- Powered by Google Gemini 2.5 Flash
- Specialized financial advice on budgeting, saving, and investing
- Real-time chat-based interactions
-
Database Integration
- MongoDB with Mongoose ODM
- Connection pooling and caching
- Optimized query performance
- Framework: Next.js 16.1.1 (App Router)
- Runtime: Node.js
- Database: MongoDB
- ODM: Mongoose 9.1.3
- Authentication: JWT (jsonwebtoken)
- Password Security: bcrypt 6.0.0
- AI Integration: Google Generative AI (Gemini 2.5 Flash)
- Additional: Ollama support
backend/
βββ src/
β βββ app/
β β βββ route.js # Root API route
β β βββ api/
β β βββ route.js # API index
β β βββ ai/
β β β βββ route.js # AI chat endpoint
β β βββ auth/
β β β βββ sign-in/
β β β β βββ route.js # User login
β β β βββ sign-out/
β β β β βββ route.js # User logout
β β β βββ sign-up/
β β β βββ route.js # User registration
β β βββ user/
β β βββ route.js # User profile endpoint
β βββ lib/
β β βββ dbConnect.js # MongoDB connection handler
β βββ models/
β β βββ userModel.js # User schema definition
β βββ utils/
β βββ bcryptUtils.js # Password hashing utilities
β βββ getUserSession.js # Session verification helper
βββ .env.local # Environment variables (create this)
βββ next.config.mjs # Next.js configuration
βββ jsconfig.json # JavaScript configuration
βββ package.json # Project dependencies
βββ README.md # This file
Before setting up the project locally, ensure you have the following installed:
- Node.js (v18.0.0 or higher) - Download here
- npm, yarn, or pnpm package manager
- MongoDB (local instance or MongoDB Atlas account)
- Google Gemini API Key - Get one here
git clone <repository-url>
cd backendnpm install
# or
yarn install
# or
pnpm installChoose one of the following options:
Option A: Local MongoDB Installation
Linux (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install -y mongodb
sudo systemctl start mongodb
sudo systemctl enable mongodbmacOS (using Homebrew):
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-communityWindows:
- Download MongoDB Community Server from MongoDB Download Center
- Run the installer and follow the setup wizard
- MongoDB will start automatically as a Windows Service
Verify MongoDB is running:
mongoshOption B: MongoDB Atlas (Cloud)
- Visit MongoDB Atlas
- Create a free account and cluster
- Whitelist your IP address
- Create a database user
- Get your connection string
Create a .env.local file in the project root:
touch .env.localAdd the following environment variables:
# MongoDB Connection
MONGODB_URI=mongodb://localhost:27017/money-mitra
# or for MongoDB Atlas:
# MONGODB_URI=mongodb+srv://<username>:<password>@<cluster>.mongodb.net/money-mitra
# JWT Secret (use a strong random string)
JWT_SECRET=your-super-secret-jwt-key-here
# Google Gemini API Key
GEMINI_API_KEY=your-gemini-api-key-here
# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:3000
# Environment
NODE_ENV=developmentGenerate a secure JWT secret:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"npm run devThe API will be available at http://localhost:3000
# Build the application
npm run build
# Start the production server
npm start| Endpoint | Method | Description | Request Body | Response |
|---|---|---|---|---|
/api/auth/sign-up |
POST | Register a new user | { firstName, lastName, email, password, role } |
JWT token in HTTP-only cookie |
/api/auth/sign-in |
POST | Authenticate existing user | { email, password } |
JWT token in HTTP-only cookie |
/api/auth/sign-out |
POST | Invalidate user session | - | Clears authentication cookie |
| Endpoint | Method | Description | Auth Required | Response |
|---|---|---|---|---|
/api/user |
GET | Get authenticated user profile | Yes (cookie) | User data (password excluded) |
| Endpoint | Method | Description | Request Body | Response |
|---|---|---|---|---|
/api/ai |
POST | Get financial advice from AI | { message: "your question" } |
{ success, reply } |
- User registers via
/api/auth/sign-upwith credentials - Password is hashed using bcrypt (10 salt rounds)
- JWT token is generated with user ID, email, and role
- Token is stored in HTTP-only cookie (expires in 1 day)
- Subsequent requests automatically include cookie
- Protected routes verify token using
getUserSessionutility
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
firstName |
String | Yes | - | User's first name |
lastName |
String | No | "" | User's last name |
email |
String | Yes | - | Unique email address |
plan |
String | No | "free" | Subscription plan (free, pro) |
points |
Number | No | 0 | User points/credits |
rank |
Number | No | 0 | User ranking |
accuracy |
Number | No | 0 | Performance accuracy metric |
twoFactorEnabled |
Boolean | No | false | 2FA status |
hashedPassword |
String | Yes | - | bcrypt hashed password |
role |
String | No | "student" | User role (student, teacher, admin) |
createdAt |
Date | Auto | - | Account creation timestamp |
updatedAt |
Date | Auto | - | Last update timestamp |
The API is configured to accept requests from the frontend URL specified in FRONTEND_URL. CORS headers are set in next.config.mjs:
- Credentials: Enabled
- Origin: Value from
FRONTEND_URLenv variable - Methods: GET, DELETE, PATCH, POST, PUT
- Headers: Accept, Content-Type
The database uses connection pooling and caching to optimize performance:
- Connection is established on first request
- Cached globally and reused across invocations
- Prevents connection pooling issues in serverless environments
curl -X POST http://localhost:3000/api/auth/sign-up \
-H "Content-Type: application/json" \
-d '{
"firstName": "John",
"lastName": "Doe",
"email": "john@example.com",
"password": "securePassword123",
"role": "student"
}'curl -X POST http://localhost:3000/api/auth/sign-in \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "securePassword123"
}' \
-c cookies.txtcurl -X GET http://localhost:3000/api/user \
-b cookies.txtcurl -X POST http://localhost:3000/api/ai \
-H "Content-Type: application/json" \
-d '{
"message": "What are some tips for saving money?"
}'- β Passwords hashed with bcrypt (never stored in plain text)
- β JWT tokens in HTTP-only cookies (XSS protection)
- β Secure cookies in production (HTTPS only)
- β CORS restricted to trusted frontend origin
- β Environment variables for sensitive credentials
- β Server-side validation on all inputs
β οΈ Ensure.env.localis in.gitignoreβ οΈ Use strong, random JWT_SECRET in productionβ οΈ Enable HTTPS in production environments
next@16.1.1- Next.js frameworkmongoose@9.1.3- MongoDB ODMjsonwebtoken@9.0.3- JWT token managementbcrypt@6.0.0- Password hashing@google/generative-ai@0.24.1- Google Gemini AI integrationollama@0.6.3- Local LLM support
Error: Please define the MONGODB_URI environment variable in .env.local
Solution: Create .env.local file and add MONGODB_URI variable.
Check Status:
mongosh --eval "db.adminCommand('ping')"Start MongoDB:
# Linux
sudo systemctl start mongodb
# macOS
brew services start mongodb-communitynpm run dev -- -p 3001Ensure JWT_SECRET in .env.local matches the secret used to sign tokens.
Verify FRONTEND_URL environment variable matches your frontend's origin.
Ensure the following are set in your production environment:
MONGODB_URI=<your-production-mongodb-uri>
JWT_SECRET=<strong-random-secret>
GEMINI_API_KEY=<your-gemini-api-key>
FRONTEND_URL=<your-frontend-production-url>
NODE_ENV=productionThe easiest way to deploy is using Vercel:
npm install -g vercel
vercelOr connect your repository on the Vercel dashboard for automatic deployments.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is private and proprietary.
For issues and questions, please contact the development team.
Built with β€οΈ for Money Mitra