Skip to content

jackstealer/habit-tracker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎯 HabitFlow - Daily Habit Tracker

A production-ready, full-stack habit tracking application built with modern technologies. Track your daily habits, maintain streaks, and visualize your progress with beautiful analytics.

HabitFlow

✨ Features

Core Features

  • User Authentication - Secure JWT-based authentication with refresh tokens
  • Habit Management - Create, edit, archive, and delete habits
  • Daily Tracking - Mark habits as complete with a single tap
  • Streak System - Automatic streak calculation with longest streak tracking
  • Analytics Dashboard - Beautiful charts and GitHub-style heatmap
  • Dark/Light Mode - Full theme support with system preference detection
  • Responsive Design - Mobile-first, works on all devices
  • Data Export - Export your data as CSV or JSON

Technical Features

  • Rate limiting and input validation
  • Secure password hashing with bcrypt
  • Token rotation for refresh tokens
  • Soft delete for habits (archive)
  • Time-zone aware tracking
  • RESTful API with versioning

πŸ—οΈ Tech Stack

Frontend

  • Framework: Next.js 14 (App Router)
  • Styling: Tailwind CSS
  • State Management: Zustand
  • Charts: Recharts
  • Animations: Framer Motion
  • HTTP Client: Axios
  • Notifications: React Hot Toast

Backend

  • Framework: NestJS
  • Database: PostgreSQL
  • ORM: Prisma
  • Authentication: Passport.js + JWT
  • Validation: class-validator
  • Rate Limiting: @nestjs/throttler

DevOps

  • Containerization: Docker & Docker Compose
  • Database Migrations: Prisma Migrate

πŸ“¦ Project Structure

tracker/
β”œβ”€β”€ frontend/                 # Next.js frontend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/             # App router pages
β”‚   β”‚   β”œβ”€β”€ components/      # React components
β”‚   β”‚   β”‚   β”œβ”€β”€ ui/          # Base UI components
β”‚   β”‚   β”‚   β”œβ”€β”€ habits/      # Habit-related components
β”‚   β”‚   β”‚   β”œβ”€β”€ analytics/   # Chart components
β”‚   β”‚   β”‚   └── layout/      # Layout components
β”‚   β”‚   β”œβ”€β”€ lib/             # Utilities and API client
β”‚   β”‚   β”œβ”€β”€ stores/          # Zustand stores
β”‚   β”‚   └── types/           # TypeScript types
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── package.json
β”‚
β”œβ”€β”€ backend/                  # NestJS backend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ auth/            # Authentication module
β”‚   β”‚   β”œβ”€β”€ users/           # Users module
β”‚   β”‚   β”œβ”€β”€ habits/          # Habits module
β”‚   β”‚   β”œβ”€β”€ analytics/       # Analytics module
β”‚   β”‚   └── prisma/          # Prisma service
β”‚   β”œβ”€β”€ prisma/
β”‚   β”‚   └── schema.prisma    # Database schema
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── package.json
β”‚
β”œβ”€β”€ docker-compose.yml        # Docker orchestration
└── README.md

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • PostgreSQL 14+ (or Docker)
  • npm or yarn

Option 1: Local Development

1. Clone and Install

# Clone the repository
git clone <repository-url>
cd tracker

# Install backend dependencies
cd backend
npm install

# Install frontend dependencies
cd ../frontend
npm install

2. Set Up Database

# Create a PostgreSQL database
createdb habit_tracker

# Or use Docker for PostgreSQL
docker run -d \
  --name habit-postgres \
  -e POSTGRES_PASSWORD=password \
  -e POSTGRES_DB=habit_tracker \
  -p 5432:5432 \
  postgres:15-alpine

3. Configure Environment Variables

Backend (.env):

DATABASE_URL="postgresql://postgres:password@localhost:5432/habit_tracker?schema=public"
JWT_SECRET="your-super-secret-jwt-key-change-in-production-123456"
JWT_EXPIRES_IN="15m"
JWT_REFRESH_SECRET="your-super-secret-refresh-key-change-in-production-789"
JWT_REFRESH_EXPIRES_IN="7d"
PORT=3001
NODE_ENV="development"
FRONTEND_URL="http://localhost:3000"
THROTTLE_TTL=60
THROTTLE_LIMIT=100

Frontend (.env.local):

NEXT_PUBLIC_API_URL=http://localhost:3001/api/v1

4. Run Database Migrations

cd backend
npx prisma generate
npx prisma migrate dev --name init

5. Start Development Servers

# Terminal 1 - Backend
cd backend
npm run start:dev

# Terminal 2 - Frontend
cd frontend
npm run dev

6. Open the App

Visit http://localhost:3000

Option 2: Docker Compose (Recommended for Production)

# Clone the repository
git clone <repository-url>
cd tracker

# Copy environment file
cp .env.example .env

# Edit .env with your secrets
# Then start all services
docker-compose up -d

# View logs
docker-compose logs -f

The app will be available at:

πŸ“š API Documentation

Authentication Endpoints

Method Endpoint Description
POST /api/v1/auth/register Register a new user
POST /api/v1/auth/login Login and get tokens
POST /api/v1/auth/refresh Refresh access token
POST /api/v1/auth/logout Logout and invalidate token
POST /api/v1/auth/change-password Change password
GET /api/v1/auth/me Get current user

Habits Endpoints

Method Endpoint Description
GET /api/v1/habits Get all habits
GET /api/v1/habits/today Get today's habits
GET /api/v1/habits/:id Get habit by ID
POST /api/v1/habits Create new habit
PATCH /api/v1/habits/:id Update habit
POST /api/v1/habits/:id/toggle Toggle habit completion
POST /api/v1/habits/:id/archive Archive habit
POST /api/v1/habits/:id/unarchive Restore habit
DELETE /api/v1/habits/:id Delete habit

Analytics Endpoints

Method Endpoint Description
GET /api/v1/analytics/dashboard Get dashboard stats
GET /api/v1/analytics/weekly Get weekly progress
GET /api/v1/analytics/monthly Get monthly progress
GET /api/v1/analytics/heatmap Get heatmap data
GET /api/v1/analytics/export Export data (CSV/JSON)

Example API Request

# Register
curl -X POST http://localhost:3001/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!",
    "firstName": "John",
    "lastName": "Doe"
  }'

# Create Habit
curl -X POST http://localhost:3001/api/v1/habits \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -d '{
    "title": "Morning Meditation",
    "description": "10 minutes of mindfulness",
    "color": "#6366f1",
    "frequency": "DAILY"
  }'

πŸ—„οΈ Database Schema

model User {
  id            String   @id @default(uuid())
  email         String   @unique
  password      String
  firstName     String
  lastName      String?
  timezone      String   @default("UTC")
  habits        Habit[]
  refreshTokens RefreshToken[]
}

model Habit {
  id            String         @id @default(uuid())
  userId        String
  title         String
  description   String?
  color         String         @default("#6366f1")
  frequency     HabitFrequency @default(DAILY)
  customDays    Int[]          @default([])
  isArchived    Boolean        @default(false)
  currentStreak Int            @default(0)
  longestStreak Int            @default(0)
  user          User           @relation(...)
  logs          HabitLog[]
}

model HabitLog {
  id        String   @id @default(uuid())
  habitId   String
  date      DateTime @db.Date
  completed Boolean  @default(false)
  habit     Habit    @relation(...)
  @@unique([habitId, date])
}

πŸ”’ Security Features

  • Password Hashing: bcrypt with 12 rounds
  • JWT Authentication: Short-lived access tokens (15m)
  • Refresh Token Rotation: New token on each refresh
  • Rate Limiting: 100 requests per minute per IP
  • Input Validation: All inputs validated and sanitized
  • CORS Protection: Configured for specific origins
  • Helmet: Security headers middleware

🚒 Deployment

Vercel (Frontend)

cd frontend
vercel --prod

Set environment variable:

  • NEXT_PUBLIC_API_URL: Your backend API URL

Railway/Render (Backend)

  1. Connect your repository
  2. Set environment variables
  3. Deploy

Docker Production

# Build and run
docker-compose -f docker-compose.yml up -d --build

# Scale if needed
docker-compose up -d --scale backend=3

πŸ§ͺ Development Commands

# Backend
npm run start:dev      # Development mode
npm run build          # Build for production
npm run start:prod     # Production mode
npm run prisma:studio  # Open Prisma Studio
npm run prisma:migrate # Run migrations

# Frontend
npm run dev           # Development mode
npm run build         # Build for production
npm run start         # Production mode
npm run lint          # Run ESLint

πŸ“ˆ Future Improvements

  • Email notifications
  • Push notifications (PWA)
  • Habit reminders (cron jobs)
  • Social features
  • Gamification badges
  • API rate limiting per user
  • Two-factor authentication
  • Data backup/restore

πŸ“„ License

MIT License - feel free to use this project for personal or commercial purposes.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


Built with ❀️ using Next.js, NestJS, and PostgreSQL

About

A full-stack habit tracking application with NestJS backend and Next.js frontend

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors