2025

HabitPledge: Financial Accountability for Habit Formation

A Next.js web application that gamifies habit formation through financial stakes, automatically donating failed pledges to charity. Built with TypeScript, Supabase, and modern React featuring real-time balance tracking, flexible habit scheduling, and comprehensive progress analytics.

HabitPledge: Financial Accountability for Habit Formation

Project Overview

HabitPledge is a Next.js-based web application that gamifies habit formation through financial stakes. Users pledge money to maintain their habits, with failed commitments automatically donated to charity. Built with TypeScript, Supabase, and a modern React stack, the platform combines behavioral psychology with charitable giving to create a unique accountability mechanism.

Core Features:

  • Habit creation with flexible frequency patterns (daily, weekly, monthly, custom)
  • Real-time balance tracking and deposit management
  • Automated pledge validation and charity integration
  • Comprehensive progress tracking with visual analytics
  • Secure authentication and role-based access control

Technical Stack:

  • Frontend: Next.js 15, React 18, TypeScript
  • Backend: Supabase (PostgreSQL, Auth, Real-time)
  • UI: Radix UI primitives, Tailwind CSS, shadcn/ui
  • State Management: React hooks with Supabase client
  • Deployment: Vercel-ready with edge functions

Problem & Motivation

Traditional habit tracking apps rely on intrinsic motivation, which often wanes over time. HabitPledge addresses this by introducing extrinsic financial incentives that create real consequences for failure.

Pain PointEffect
Lack of accountability in habit formationUsers abandon habits within weeks
No consequences for missed commitmentsMotivation decreases over time
Isolated habit trackingNo community or external impact
Complex habit schedulingUsers struggle with realistic goal-setting
Limited progress visualizationUsers can’t see long-term patterns

System Architecture

The application follows a modern full-stack architecture with clear separation of concerns:

User Interface (Next.js App Router)

Authentication Layer (Supabase Auth)

API Layer (Supabase Client)

Database Layer (PostgreSQL + RLS)

External Services (Charity APIs)

Key Modules:

  • Auth Module: Handles user registration, login, and session management
  • Habit Management: CRUD operations for habit creation, editing, and tracking
  • Balance System: Manages deposits, pledges, and financial calculations
  • Progress Tracking: Logs habit completion and generates analytics
  • Charity Integration: Manages charity selection and donation processing

Design Choices

Database Design:

  • Row Level Security (RLS): Every table enforces user-specific access, ensuring data isolation
  • Normalized Schema: Separate tables for profiles, habits, logs, and charities to maintain data integrity
  • Materialized Views: account_balances and balance_history provide real-time financial calculations
  • Triggers: Automated balance validation prevents over-pledging

Frontend Architecture:

  • App Router: Leverages Next.js 15’s file-based routing for better performance and SEO
  • Component Composition: Reusable UI components built on Radix primitives for accessibility
  • Type Safety: Full TypeScript integration with generated database types
  • Responsive Design: Mobile-first approach with Tailwind CSS utilities

Security Considerations:

  • Client-side Validation: Form validation prevents invalid data submission
  • Server-side Enforcement: Database constraints and triggers provide final validation
  • Authentication Guards: Route protection ensures authenticated access to sensitive data

Technical Deep Dive

Authentication & Session Management

The application uses Supabase Auth for secure user management with automatic session handling.

// lib/supabase/client.ts
import { createClient } from '@supabase/supabase-js';
import { Database } from '@/lib/database.types';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error('Missing Supabase environment variables');
}

export const supabase = createClient<Database>(supabaseUrl, supabaseAnonKey);

The client is configured with TypeScript types generated from the database schema, ensuring type safety across the entire application.

Database Schema & Relationships

The core data model supports complex habit tracking with financial accountability:

-- supabase/migrations/20250215235125_golden_boat.sql
CREATE TABLE habits (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid REFERENCES profiles(id) NOT NULL,
  title text NOT NULL,
  description text,
  frequency text NOT NULL,
  target_days integer NOT NULL,
  pledge_amount decimal(10,2) NOT NULL,
  charity_id uuid REFERENCES charities(id),
  status text DEFAULT 'active',
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now(),
  CONSTRAINT valid_frequency CHECK (frequency IN ('daily', 'weekly')),
  CONSTRAINT valid_status CHECK (status IN ('active', 'paused', 'completed'))
);

The schema includes constraints for data validation and foreign key relationships for referential integrity.

Balance Management System

A sophisticated balance tracking system prevents users from pledging more than they have available:

-- supabase/migrations/20250216020345_add_account_balance.sql
CREATE VIEW account_balances AS
SELECT 
  p.id as user_id,
  COALESCE(d.total_deposits, 0) - COALESCE(h.total_pledged, 0) as current_balance
FROM profiles p
LEFT JOIN (
  SELECT user_id, SUM(amount) as total_deposits
  FROM deposits
  GROUP BY user_id
) d ON p.id = d.user_id
LEFT JOIN (
  SELECT user_id, SUM(pledge_amount) as total_pledged
  FROM habits
  WHERE status = 'active'
  GROUP BY user_id
) h ON p.id = h.user_id;

This view calculates real-time balances by subtracting active pledges from total deposits.

Habit Creation & Validation

The habit creation process includes comprehensive validation and balance checking:

// app/(dashboard)/habits/new/page.tsx
const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  setLoading(true);

  try {
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) {
      router.push('/login');
      return;
    }

    const { error } = await supabase.from('habits').insert([
      {
        user_id: session.user.id,
        title: formData.title,
        description: formData.description,
        frequency: formData.frequency,
        target_days: parseInt(formData.target_days),
        pledge_amount: parseFloat(formData.pledge_amount),
        times_per_week: formData.frequency === 'weekly_custom' ? parseInt(formData.times_per_week) : null,
        times_per_month: formData.frequency === 'monthly_custom' ? parseInt(formData.times_per_month) : null,
      },
    ]);

    if (error) {
      if (error.message.includes('Insufficient balance')) {
        toast({
          title: 'Insufficient Balance',
          description: error.message,
          variant: 'destructive',
        });
        return;
      }
      throw error;
    }
  } catch (error: any) {
    // Error handling
  }
};

The system validates balance sufficiency through database triggers before allowing habit creation.

Dashboard Analytics

Real-time analytics provide users with comprehensive progress insights:

// app/(dashboard)/dashboard/page.tsx
const [stats, setStats] = useState({
  activeHabits: 0,
  completedHabits: 0,
  totalPledged: 0,
  streakDays: 0,
});

// Calculate stats from habits data
const currentHabits = habitsData.length;
const completedHabits = habitsData.filter(h => h.status === 'completed').length;
const totalPledged = habitsData.reduce((sum, habit) => sum + Number(habit.pledge_amount), 0);

setStats({
  activeHabits: currentHabits,
  completedHabits,
  totalPledged,
  streakDays: calculateLongestStreak(habitsData),
});

The dashboard aggregates data from multiple sources to provide actionable insights.

Data Management & Analytics

HabitPledge implements a comprehensive data management system for tracking user progress and financial commitments:

Data Collection:

  • Habit completion logs with timestamps and user context
  • Financial transaction history for pledge patterns
  • User interaction metrics for feature optimization

Analytics Processing:

  • Real-time aggregation of completion rates and streaks
  • Balance calculations with automatic validation
  • Progress visualization with historical trend analysis

Validation & Monitoring:

  • Database constraints ensure data integrity
  • RLS policies enforce security boundaries
  • Error handling provides graceful degradation

Performance & User Experience

The application optimizes for real-time performance and seamless user interactions:

Caching Strategy:

  • Supabase client maintains connection pooling
  • React Query patterns for optimistic updates
  • Local state management for immediate UI feedback

Performance Optimizations:

  • Database views for complex calculations
  • Indexed queries for fast habit retrieval
  • Lazy loading for transaction history

Real-time Updates:

// components/sidebar.tsx
const handleSignOut = () => {
  router.push('/');  // Redirect immediately
  supabase.auth.signOut();  // Sign out in the background
};

The application provides immediate feedback while handling background operations asynchronously.

What’s Next

Immediate Roadmap:

  • Mobile App: React Native implementation for iOS/Android
  • Social Features: Friend challenges and community leaderboards
  • Advanced Analytics: Machine learning insights for habit success prediction
  • Charity Integration: Direct API connections for automated donations

Technical Enhancements:

  • Real-time Notifications: WebSocket integration for instant updates
  • Offline Support: Service worker implementation for offline habit tracking
  • Performance Monitoring: Advanced analytics and error tracking
  • API Rate Limiting: Protection against abuse and spam

Scalability Improvements:

  • Microservices Architecture: Separation of concerns for better scaling
  • CDN Integration: Global content delivery for improved performance
  • Database Optimization: Query optimization and connection pooling
  • Security Hardening: Advanced threat detection and prevention

HabitPledge represents a novel approach to habit formation, combining behavioral psychology with charitable giving through modern web technologies. The application’s architecture demonstrates how thoughtful design choices can create both engaging user experiences and robust, scalable systems.

Last updated on August 24, 2025 at 12:16 PM EST. See Changelog

Explore more projects