Experience the platform live in production:
- Frontend Dashboard: https://carbon-sphere-ai.vercel.app/ (Hosted on Vercel)
- Backend REST API: https://carbonsphere-ai-production.up.railway.app/ (Hosted on Railway)
- Database Cluster: MongoDB Atlas (Shared Serverless Cluster)
- System Status:
Active🟢 (Health check endpoint/api/healthmonitored)
Global climate initiatives suffer from several structural roadblocks when implemented at individual or organizational levels:
- The Actionability Gap: Traditional carbon calculators provide users with static raw data (e.g., "Your footprint is 1.2 tCO₂e"). This data lacks context, leaving users with no clear path to lower it.
- Information Overload: Existing suggestions are generic and fail to adjust to a user's geographical location, actual daily routine, dietary restrictions, or transport habits.
- Engagement Decay: Users quickly abandon tracking when there are no milestones, feedback loops, or community validation mechanism.
- Prediction Deficit: Without forecasting, users cannot visualize the long-term impact of their immediate adjustments, preventing proactive environmental strategies.
CarbonSphere AI is a state-of-the-art ESG management and carbon tracking platform that converts raw environmental logs into highly personalized, AI-driven abatement plans.
Instead of static lookups, CarbonSphere AI uses a dynamic sustainability intelligence engine powered by Groq (Llama 3.3 70B). It processes real-time activity logs, runs weighted linear regression models to project future emissions, runs scenario simulations, and auto-generates adaptive weekly actions that adjust dynamically as the user changes their routine.
- What it does: Performs semantic analysis on user activity trends, generates monthly executive summaries, isolates major emissions categories, and drafts a custom weekly roadmap.
- Why it matters: Users receive direct, personalized priorities instead of filtering through spreadsheets.
- Technical Implementation: Node service aggregates user's activity logs and prompts Llama 3.3 via a structured JSON-mode schema to output structured markdown plans.
- What it does: Provides a persistent, context-aware chatbot trained on the user's carbon footprint data.
- Why it matters: Answers specific inquiries (e.g., "How much carbon do I save if I take the train instead of driving today?").
- Technical Implementation: Next.js UI using SSE streams connecting to a backend controller populated with recent user stats and active forecast metrics.
- What it does: Supports high-fidelity carbon logging across 6 categories: Transport, Energy, Food, Shopping, Waste, and Water.
- Why it matters: Simplifies daily logging while converting distinct metrics (e.g., miles driven, therms burned) into uniform metric tons of CO₂ equivalent (tCO₂e).
- Technical Implementation: Schema-driven Mongoose model mapping inputs to specific conversion coefficients directly on save.
- What it does: Predicts a user's emissions trajectory up to 6 months into the future.
- Why it matters: Provides a baseline reference showing where the user is heading if no action is taken.
- Technical Implementation: Express-based regression module executing time-decay weighted linear regressions on historical data points.
- What it does: Allows users to drag-and-drop structural lifestyle changes (e.g., installing solar panels, replacing a gasoline car with an EV) to see projected reductions.
- Why it matters: Demonstrates financial and ecological ROI prior to capital outlay.
- Technical Implementation: Client-side sandbox executing mathematical calculations dynamically overlaying baseline trajectories.
- What it does: Gamifies the carbon reduction journey via category-specific goals (e.g., "Meatless Week") and unlockable achievements.
- Why it matters: Retains user interest and leverages social competition to drive sustainability.
- Technical Implementation: Trigger-based backend validators checking activity log thresholds upon daily updates.
- What it does: Integrates a verified catalog of carbon offset initiatives (e.g., reforestation, wind farms) where users can "purchase" credits to balance their footprint.
- Why it matters: Closes the loop on emissions that cannot be directly reduced.
- Technical Implementation: Backend model mapping purchases to users, incrementing
totalCarbonSavedstatistics.
- What it does: Automatically compiles monthly ESG scorecards and category metrics.
- Why it matters: Ready for submission to corporate compliance partners or personal archival.
- Technical Implementation: Client-side HTML-to-Canvas rendering exporting A4 portrait PDFs via
jsPDFat 2x scale.
CarbonSphere AI integrates the Groq SDK utilizing Llama 3.3 70B to power its intelligence layer:
[User Action Logs] ---> [Mongoose Aggregator] ---> [Groq Prompt Builder] ---> [Llama 3.3 70B] ---> [Structured JSON Output] ---> [AI Coach/Assistant UI]
- Multi-Key Failover Loop: To prevent rate limiting and key exhaustion during high-concurrency periods, the backend utilizes a round-robin API key distribution cycle. If a key fails or encounters rate limits, the loop transparently switches to the next available token.
- Context Injection: Prompt templates inject the user's localized settings, carbon averages, active forecasts, and challenge history, preventing the AI from generating generic advice.
- JSON-Schema Conformance: System prompts dictate strict JSON response configurations which are validated prior to client delivery, securing UI element integrity.
The forecasting module does not rely on random values. It implements a mathematically rigorous Weighted Linear Regression with time-decay heuristics:
-
Weighted Data Points: Historical data is weighted using a linear multiplier
$(i + 1)$ , meaning recent months have a greater impact on the slope than older months. -
Granular Fallbacks:
- If 1 month of data exists: The engine aggregates daily logs, estimates a daily slope, and extrapolates it to 30 days.
- If 1 day of data exists: The engine falls back to a category-specific growth vector (e.g., 5% baseline transport increase).
-
Active Deduction Engine: When projecting 3-month and 6-month horizons, the algorithm query-intersects the database for active sustainability commitments, subtracting their expected savings from the projected emissions line:
$$\text{Projected}_t = (\text{Intercept} + \text{Slope} \times t) - \text{ActiveReduction}$$
CarbonSphere AI operates on a highly decoupled, modern, and scalable architecture separating the UI presentation layer from the robust data-processing backend. The ecosystem leverages Next.js for high-performance React rendering, Express.js for RESTful API services, MongoDB Atlas for serverless data persistence, and Groq's Llama 3.3 for high-throughput AI intelligence.
graph TD
subgraph "Frontend Layer (Vercel)"
UI[Next.js App Router]
Tailwind[TailwindCSS + Shadcn UI]
State[React Hooks + Context]
UI --> Tailwind
UI --> State
end
subgraph "Backend Layer (Railway)"
API[Express.js API]
Auth[JWT + CSRF Auth Layer]
Router[API Routers & Controllers]
Services[Business Logic Services]
API --> Auth
Auth --> Router
Router --> Services
end
subgraph "Data & AI Layer"
Mongo[(MongoDB Atlas)]
Groq{Groq Llama Models}
end
Client([Client Browser]) -->|HTTPS / REST| UI
UI -->|HTTPS / API Calls| API
Services <-->|Mongoose ODM| Mongo
Services <-->|Groq SDK| Groq
The following ER diagram illustrates the core MongoDB collections and their logical relationships:
erDiagram
USER ||--o{ ACTIVITY : logs
USER ||--o{ OFFSET_PURCHASE : makes
USER ||--o{ USER_CHALLENGE : joins
USER ||--o{ FORECAST : generates
ACTIVITY {
ObjectId _id
String userId
String category
String activityType
Number carbonEmission
Date date
}
OFFSET_PURCHASE {
ObjectId _id
String userId
String projectId
Number creditsBought
Date purchaseDate
}
USER_CHALLENGE {
ObjectId _id
String userId
String challengeId
String status
Number progress
}
- Client Interaction: The user interacts with the Next.js frontend (e.g., logging an activity or requesting AI insights).
- API Request Initiation: The frontend
apiClientsecurely attaches the JWT and dynamically fetched Cross-Origin CSRF token to the request headers. - Backend Middleware Processing: The Express.js backend intercepts the request, validates the CORS origin, verifies rate limits via
express-rate-limit, decodes the JWT, and validates the CSRF token. - Controller Execution: The validated request reaches the corresponding controller (e.g.,
aiCoachController), which requests required data from MongoDB. - Response Delivery: Data is processed, formatted, and returned to the frontend, updating the React state and reflecting on the UI.
CarbonSphere AI employs an enterprise-grade security posture:
- Authentication: Stateless JSON Web Tokens (JWT) stored securely.
- Cross-Origin CSRF Protection: A robust Double Submit Cookie implementation natively engineered to protect against cross-site request forgery across the decoupled Vercel/Railway boundaries.
- Network Security: Strict CORS policies,
Helmet.jsHTTP headers, and API rate limiting prevent abuse and brute-force attacks.
The intelligence layer acts as a specialized data-processor rather than a generic chatbot:
- Data Aggregation: User metrics (activities, forecasts, limits) are aggregated via optimized MongoDB queries.
- Contextual Prompt Building: The backend constructs highly structured prompts injecting the user's specific environmental data.
- Groq Inference: The prompt is dispatched to Groq's Llama 3.3 model enforcing a strict JSON-mode schema.
- Validation & Delivery: The output is parsed and validated before being served to the frontend, guaranteeing predictable UI rendering.
- Frontend (Vercel): The Next.js application is deployed to Vercel's Edge Network, utilizing static pre-rendering and efficient edge caching for near-instant Time to Interactive (TTI).
- Backend (Railway): The Node.js/Express.js API runs on Railway, providing a scalable containerized environment optimized for heavy database transactions and AI API orchestration.
- Database (MongoDB Atlas): Hosted on a serverless Atlas cluster to ensure high availability and resilient disaster recovery.
The following sequence diagram illustrates a specific AI data request across these layers:
sequenceDiagram
autonumber
actor User as Client Dashboard (Next.js)
participant API as Express Server (Node.js)
participant DB as MongoDB Atlas
participant AI as Groq (Llama 3.3)
User->>API: HTTP Request (With Secure Cookie & JWT)
Note over API: CORS Verification & CSRF Validation
API->>DB: Query Aggregated Activity Data
DB-->>API: Return User Footprint & Preferences
API->>AI: Send Rich Prompt Context (JSON Mode)
AI-->>API: Stream Back Structured Insights
API->>DB: Save Generated Recommendations
API-->>User: Return HTTP 200 (Payload)
- Framework: Next.js 15 (App Router, Client-side Navigation)
- Runtime UI: React 19, TypeScript
- Styling: TailwindCSS, TailwindCSS-Animate, lucide-react
- Visualizations: Recharts (Fully customized for dark mode compatibility)
- Component Library: shadcn/ui (Radix primitives)
- Routing & Framework: Express.js 5.x
- Logger: Winston Logger (Configured with file rotators and console prints)
- Security Primitives: Helmet, Express Rate Limit, Cookie Parser, bcryptjs
- Storage: MongoDB Atlas
- ORM: Mongoose (Using compound index definitions for optimized lookup paths)
- Frontend Unit: Vitest & React Testing Library
- End-to-End & Smoke: Playwright (Including accessibility testing using
@axe-core/playwright) - Backend Integration: Vitest & Supertest
- Secure Session Transport: Authentication is managed using HTTP-Only cookies. In production, cookies enforce
SameSite=NoneandSecure=trueheaders to ensure compatibility across decoupled client-server environments. - CORS Protection: Dynamic origin validation evaluates the
Originheader against a whitelist, explicitly permitting local development environments, production hostnames, and Vercel preview domains (*.vercel.app). - Access Rate Limiting: Enforces strict limits:
- Global API API Limits: 100 requests per 15 minutes.
- Auth Endpoint Limits: 5 requests per 15 minutes on
/api/auth/loginand/api/auth/register.
- Fail-Safe Startup Verification: The backend process checks for the existence of
JWT_SECRETand MongoDB connection paths on startup, terminating instantly if security parameters are missing.
The repository includes a comprehensive testing matrix to ensure stability across deployments:
# Execute frontend unit & component tests (Vitest)
pnpm test
# Execute Playwright E2E & automated accessibility audits
pnpm test:e2e
# Execute backend integration tests (Vitest + MongoDB Memory Server)
cd backend && npm run test- Frontend Cards: Validation of
AIInsightCard.test.tsx,CarbonScoreCard.test.tsx,GoalProgressCard.test.tsx(Component validation). - Playwright Smoke & Auth: Integration testing covering registration, session validation, and layout routing.
- Axe Accessibility Auditing: Playwright-based checks to ensure the application conforms to WCAG 2.1 AA benchmarks.
- Backend Integration Specs: Endpoint verification across
auth.test.js,forecast.test.js,simulator.test.js, andactivity.test.js.
- In-Flight Request Deduplication: The frontend
apiClientuses a custom caching utility (apiCache.ts) that maps pending requests. Multiple simultaneous requests to the same endpoint share the same promise, preventing server flooding. - Mongoose Index Optimization: Database queries utilize compound indexes to prevent full collection scans:
ActivitySchema.index({ userId: 1, date: -1 })(Optimizes history sorting)ActivitySchema.index({ userId: 1, category: 1 })(Optimizes categories grouping)
- Next.js Route Optimization: Employs Route Handlers and optimized client bundle routing. Next.js statically pre-renders all dashboard subpages, reducing Time to Interactive (TTI).
Follow these steps to run CarbonSphere AI on your local machine:
git clone https://github.com/hetpatel1b/CarbonSphere-AI.git
cd CarbonSphere-AI
pnpm installCreate a .env.local file in the root directory:
NEXT_PUBLIC_API_URL="http://localhost:5000/api"Create a .env file in the backend/ directory:
PORT=5000
MONGODB_URI="mongodb://localhost:27017/carbonsphere"
JWT_SECRET="use_a_strong_random_signing_key_here"
FRONTEND_URL="http://localhost:3000"
GROQ_API_KEY_1="your_groq_api_key_1"Seed achievements and challenge templates:
cd backend
npm run seed:challenges
npm run seed:achievements
cd ..Run the backend server:
cd backend && npm run devRun the Next.js frontend (in a separate terminal):
pnpm devCarbonSphere AI utilizes a robust, production-ready security architecture that strictly isolates offline demonstration modes from live backend networks.
The platform features a client-side "Demo Mode" (demoInterceptor.ts) designed to allow judges and guests to experience the UI without a database connection.
- Network Isolation: When enabled via
localStorage, the interceptor mocks HTTP responses entirely within the browser memory. - No Backend Access: Demo Mode does NOT bypass backend authentication. Any request that escapes the interceptor will still be rejected by the Express backend with a
401 Unauthorizedif a valid JWT is not present. - No Data Leakage: The mock data is purely hardcoded generic data. No real user metrics, emails, or password hashes are bundled into the frontend.
- Persistent Banner Alert: If Demo Mode is activated, a persistent
DemoModeBanneris dynamically injected into the React Tree, ensuring judges are 100% aware that the UI is using local mock data. - Strict JWT + CSRF Authentication: Real user sessions are secured via
httpOnlysecure cookies. Cross-Site Request Forgery (CSRF) tokens are strictly validated on every mutating request (POST,PUT,DELETE).
- Distributed Caching: Add Redis to synchronize API rate limiting variables and cache database counts globally.
- Team workspaces: Allow multiple users to aggregate data under a corporate profile.
- Vector DB Cache: Introduce Pinecone or PGVector to cache LLM recommendations for recurring carbon categories, minimizing Groq costs.
- Contributors: Developed by Het Patel.