DEV Community

Cover image for How I Built AirSense - A Production-Ready MERN + Generative AI Air Quality Ecosystem
Rishabhh Pandey
Rishabhh Pandey

Posted on

How I Built AirSense - A Production-Ready MERN + Generative AI Air Quality Ecosystem

Existing Air Quality Dashboards Just Show Numbers. No Context. No Forecasts. No Actionable Insights.

So I Built AirSense — A Full-Stack Air Quality Monitoring Ecosystem That Combines Real-Time Data With Generative AI.

Here Is The Complete Breakdown Of How It Works.

🛠️ The Tech Stack

  • Frontend - React.Js + Tailwind CSS
  • Backend - Node.Js + Express.Js
  • Database - MongoDB + Mongoose
  • Real-Time - Socket.IO
  • AI Layer - Groq LLM
  • Cloud - Cloudinary + WAQI API
  • Authentication - JWT With 2FA And OTP Verification

🌬️ Core Features

Real-Time Monitoring

A Multi-Station AQI Dashboard With Live Updates Via Socket.IO. Color-Coded Heatmaps Across All Monitoring Stations. A 24-Hour Timeline Scrubber And Trend History. Every New Reading Pushes Instantly To Connected Clients Without A Page Refresh.

Generative AI Layer Powered By Groq LLM

  • AI Insight Narrator — Plain-English AQI Explanations With Exact Numbers
  • Anomaly Explainer — Detects Unusual Pollution Patterns And Suggests Causes
  • Health Advisory Writer — Real-Time Precautions For Sensitive Zones Like Schools And Hospitals
  • Pollution Source Narrator — Explains Why A Specific Pollutant Dominates At A Station
  • Compliance Summarizer — Regulatory Insights For WHO US EPA CPCB And EU Standards
  • Report Writer — AI-Generated Executive Reports For Any Time Period
  • KPI Advisor — Recommends Which Metrics To Focus On Based On Live Data
  • Trend Explainer — Breaks Down Why A Metric Moved Up Down Or Stayed Stable

Forecasting Engine

Statistical Time-Series Forecasting Using Linear Regression. Predictions For 12-Hour 7-Day And 30-Day Horizons. Every Forecast Is Enhanced With AI-Generated Explanations And Confidence Scoring. Also Supports Side-By-Side Forecast Comparison Across Multiple Stations.

Multi-Standard Compliance

Instantly Check Pollutant Levels Against WHO US EPA CPCB And EU Standards. Each Reading Is Graded As Pass Or Fail With Exceedance Percentage Calculated Automatically.

Pollution Source Attribution

AI Analyzes And Attributes Pollution To Sources Like Traffic Industrial Construction Crop Burning Natural And Other. Each Source Comes With Impact Metrics For Population Health Economy And Carbon Footprint.

🤖 The AI Layer In Detail

Every AI Feature Runs On Groq LLM Using Two Models. The Primary Model Is openai/gpt-oss-120b For Complex Reasoning And The Secondary Model Is llama-3.1-8b-instant For Faster Simpler Tasks.

Key Engineering Decisions

  1. JSON Mode

Every Prompt Forces The LLM To Return Valid JSON. This Prevents Parsing Errors And Broken UI. Without JSON Mode The AI Sometimes Returns Markdown Or Plain Text Which Crashes The Frontend Parser.

  1. cleanValue Helper

The AI Sometimes Returns Placeholder Values Like A Hyphen Or N/A Or Empty Strings. This Helper Sanitizes Them Before They Reach The Frontend. It Also Filters Out The String Null And Unknown Values.

  1. sessionSeed

A Random 6-Character String Is Injected Into Every Prompt. This Prevents The AI From Repeating The Same Answer On Every Call. Without This Trick The Model Would Return Identical Responses Due To Caching And Temperature Behaviour.

  1. Post-Processing

After Every AI Response Arrays Are Filtered To Remove Invalid Values. Generation Plus Cleanup Is The Reliable Pattern. Every Array Field Like Insights Causes Fixes Recommendations Factors And Actions Goes Through This Cleanup Step.

  1. Temperature Tuning

Different AI Services Use Different Temperature Settings. Creative Tasks Like Copywriting Use Higher Temperature Around 0.85 While Deterministic Tasks Like Station Description Writing Use Lower Temperature Around 0.3.

📊 Forecasting Is Not AI But Enhanced By It

The Prediction Itself Uses Linear Regression Which Is A Statistical Method. Not A Neural Network. Not A Transformer. Just Classic Maths.

But Every Forecast Is Enhanced With -

  • AI-Generated Explanations Of The Trend
  • Confidence Scoring That Decreases With Horizon
  • Health Advisory Recommendations Based On Predicted AQI
  • Weather Impact Analysis

This Hybrid Approach Is What Modern Production Apps Actually Use. Not Everything Needs To Be AI. Sometimes A Simple Statistical Model Plus AI Explanation Is Better Than An Overcomplicated Neural Network.

🔐 Security Architecture

  • JWT Authentication With 2FA
  • OTP Verification Via Email For Registration And Password Reset
  • Role-Based Access Control For Admin And User Roles
  • Session Management With Full Audit Trail
  • Password Hashing With Bcrypt
  • Rate Limiting On Sensitive Endpoints
  • CORS Configuration For Frontend Only
  • Environment Variables For All Secrets

💡 Key Challenges And Learnings

Challenge 1 - AI Output Reliability

Sometimes The AI Returned Placeholder Values Empty Arrays Or Even Broke JSON Format. This Was Fixed With A Three-Layer Approach. First Force JSON Mode At The API Level. Second Sanitize Every Value With The cleanValue Helper. Third Filter Arrays During Post-Processing.

Challenge 2 - Real-Time Sync

The Dashboard Needed Live Updates Without Refreshing. This Was Solved With Socket.IO Room-Based Subscriptions Using station-id Format. Each Client Joins Only The Rooms It Needs. This Keeps Bandwidth Low And Updates Instant.

Challenge 3 - Stateless Uploads

Storing Images On The Server Would Break In Serverless Deployments. This Was Solved By Using Cloudinary Streaming API Instead Of Local Disk Storage. The File Buffer Goes Directly To Cloudinary And Only The HTTPS URL Is Stored In MongoDB.

Challenge 4 - Multi-Standard Compliance Logic

Each Regulatory Body Has Different Limits For Each Pollutant. This Was Solved With A Central LIMITS Object That Maps Every Standard-Pollutant Combination To Its Threshold Value. Adding A New Standard Only Requires Updating This One Object.

🎯 What Comes Next

I Am Currently Working On Adding LSTM Neural Networks For Forecasting To Push Accuracy Higher Than Linear Regression. The Plan Is To Train The Model On Historical AQI Data And Use TensorFlow.Js For Direct Node.Js Integration Without Needing A Separate Python Service.

Other Planned Features Include -

  • Real Payment Gateway Integration
  • Mobile App Using React Native
  • Public API For Third-Party Developers
  • Advanced Historical Analytics Dashboard

📌 Final Thoughts

Building AirSense Taught Me That Production AI Is Not Just About Calling An LLM. It Is About Prompt Engineering Error Handling Post-Processing And Delivering Clean Data To Users.

The Biggest Lesson Was That Reliability Matters More Than Cleverness. A Simple JSON Mode Plus Cleanup Logic Beats An Elaborate Prompt That Sometimes Fails.

Interested In The Full Source Code Or Getting This For Your Portfolio?

🌐 https://www.theprojectstack.com/

Happy To Answer Any Questions About The Architecture Or AI Integration. Drop A Comment Below!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.