I Built an AI Flood Forecasting System with Next.js 15 & FastAPI - Here's How 🌊
Akshat Raj

Akshat Raj @akshatraj00

About: Akshat Raj | AI Engineer & Full-Stack Innovator Founder of OnePersonAI, building next-gen intelligent systems that merge Artificial Intelligence, Web Automation, and Machine Learning to create.

Joined:
Aug 5, 2025

I Built an AI Flood Forecasting System with Next.js 15 & FastAPI - Here's How 🌊

Publish Date: Oct 12
4 0


I Built an AI Flood Forecasting System with Next.js 15 & FastAPI - Here's How 🌊

Hey developers! 👋

I just finished building a real-time flood forecasting system using Next.js 15, FastAPI, and Machine Learning. Here's the complete breakdown!

🔥 Live Demo

👉 https://flood-forecast-ai.vercel.app

💻 Source Code

👉 https://github.com/AkshatRaj00/flood-forecast-ai


🎯 What I Built

A production-ready dashboard that:

  • ✅ Monitors 8 river stations in real-time
  • ✅ Predicts floods 7 days ahead using AI
  • ✅ Updates every 30 seconds via WebSockets
  • ✅ Shows live weather data from OpenWeatherMap
  • ✅ Interactive map with color-coded alerts

🛠️ Tech Stack

Frontend:
{
"framework": "Next.js 15 (with Turbopack)",
"language": "TypeScript",
"styling": "Tailwind CSS",
"maps": "Leaflet.js",
"deployment": "Vercel"
}

text

Backend:
{
"framework": "FastAPI",
"language": "Python 3.11",
"ml_libs": ["NumPy", "Scikit-learn"],
"real_time": "WebSockets",
"deployment": "Railway (planned)"
}

text


🏗️ Architecture

Frontend (Vercel) ←→ WebSocket ←→ Backend (Railway)

OpenWeatherMap API

text


💡 Code Highlights

1. Real-Time WebSocket Connection

// frontend/src/app/page.tsx
useEffect(() => {
const ws = new WebSocket('ws://localhost:8000/ws');

ws.onmessage = (event) => {
const message = JSON.parse(event.data);

text
if (message.type === 'real_time_update') {
setStations(message.data);
setPredictions(message.predictions);
}
};

return () => {
if (ws.readyState === WebSocket.OPEN) {
ws.close();
}
};
}, []);

text

2. AI Prediction Model

backend/ml_predictor.py
def generate_predictions(station_data):
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

text
predictions = []

for station in station_data:
X = np.array().reshape(-1, 1)[1]
y = np.array([station['water_level']] * 7)

poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)

model = LinearRegression()
model.fit(X_poly, y)

future_X = np.array().reshape(-1, 1)
forecast = model.predict(poly.transform(future_X))

predictions.append({
    "forecast_7day": forecast.tolist(),
    "confidence": 0.85
})
Enter fullscreen mode Exit fullscreen mode

return predictions
text

3. FastAPI WebSocket Handler

backend/main.py
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()

text
try:
while True:
station_data = await fetch_real_time_data()
predictions = generate_predictions(station_data)

    await websocket.send_json({
        "type": "real_time_update",
        "data": station_data,
        "predictions": predictions
    })

    await asyncio.sleep(30)
Enter fullscreen mode Exit fullscreen mode

except WebSocketDisconnect:
print("Client disconnected")
text


🐛 Challenges I Faced

1. TypeScript Path Aliases on Vercel

Problem: @/types imports failing

Solution: Used relative imports ../../types

2. Leaflet SSR Issues

Problem: Map requires window object

Solution: Dynamic import with ssr: false

const Map = dynamic(() => import('./components/Map'), {
ssr: false
});

text

3. WebSocket Reconnection

Problem: Connection drops on tab switch

Solution: Auto-reconnect logic + cleanup


📊 Performance

✅ Build size: 117 KB
✅ First Load JS: 118 KB
✅ Build time: ~7 seconds
✅ Lighthouse Score: 90+

text


🚀 Deployment

Frontend (Vercel)

npm run build

Auto-deploys on git push
text

Backend (Railway)

Procfile
web: uvicorn main:app --host 0.0.0.0 --port $PORT

text


📸 Screenshots

[Include 2-3 screenshots of your dashboard]


🎓 What I Learned

  1. WebSockets are amazing for real-time apps
  2. TypeScript saves hours of debugging
  3. Next.js 15 with Turbopack is blazing fast
  4. FastAPI makes Python backends beautiful
  5. Deployment requires careful optimization

🔜 Next Steps

  • Deploy backend to Railway
  • Add PostgreSQL for historical data
  • SMS/Email alerts
  • Mobile app version

💬 Questions?

Drop them in the comments! I'm happy to help! 👇

If you found this helpful, don't forget to ❤️ and 🦄!


🔗 Links

Happy coding! 🚀
🏆 SEO KEYWORDS TO USE:
text

  • Next.js 15 tutorial
  • FastAPI WebSocket
  • Real-time dashboard
  • AI flood prediction
  • Machine learning project
  • Full-stack TypeScript
  • Disaster management system
  • Leaflet.js tutorial
  • Vercel deployment
  • Python FastAPI project
  • WebSocket real-time
  • Climate tech project
  • OpenWeatherMap integration
  • Production deployment

Comments 0 total

    Add comment