Privacy-Focused-Web-Analytics-Dashboard

Frontend-Backend Integration Guide

← Back to README Documentation Index Project Structure API Docs

πŸ“Š Overview

This guide explains how the frontend Dashboard connects to the backend API to display real data instead of hardcoded mock values.


πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Frontend (React)                 β”‚
β”‚   Dashboard.tsx                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
        Uses hooks (useDashboardData)
               β”‚
               ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   React Hooks (useDashboardData)    β”‚
β”‚   client/hooks/useDashboardData.ts  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
        Fetch with Authorization
               β”‚
               ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚      Backend (Express.js)            β”‚
β”‚   /api/v1/dashboard/* endpoints     β”‚
β”‚   server/routes/dashboard.ts        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
        Query Database
               β”‚
               ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   SQLite Database                    β”‚
β”‚   prisma/dev.db                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🎯 What’s Been Implemented

1. βœ… API Endpoints Created

Location: server/routes/dashboard.ts

Endpoints available:

All endpoints require: Authorization: Bearer {token}

2. βœ… React Hooks Created

Location: client/hooks/useDashboardData.ts

Available hooks:

useDashboardData(dateRange); // Fetch all data
useDashboardMetrics(dateRange); // Fetch metrics only
useChartData(dateRange, type); // Fetch chart data
useTopPages(); // Fetch top pages
useReferrers(); // Fetch referrers
useDeviceDistribution(); // Fetch device data
useTopLocations(); // Fetch location data

Each hook returns:

{
  data: T | null,     // The fetched data
  loading: boolean,   // Loading state
  error: string | null // Error message if failed
}

3. βœ… TypeScript Types Created

Location: shared/types/dashboard.ts

4. βœ… API Routes Registered

Modified: server/index.ts

Dashboard routes mounted at /api/v1/dashboard


πŸ”„ How to Use in Dashboard Component

Before (Hardcoded Mock Data)

export default function Dashboard() {
  const [darkMode, setDarkMode] = useState(false)

  return (
    <MetricCard
      title="Page Views"
      value="45,231"        // ← Hardcoded
      trend={12}
      // ...
    />
  )
}

After (Using Real API Data)

import { useDashboardData } from "@/hooks/useDashboardData"

export default function Dashboard() {
  const [darkMode, setDarkMode] = useState(false)
  const [dateRange, setDateRange] = useState("7d")

  // Fetch data from API
  const { data, loading, error } = useDashboardData(dateRange)

  if (loading) return <DashboardSkeleton />
  if (error) return <ErrorState message={error} />
  if (!data) return <EmptyState />

  // Format metrics for display
  const pageViewsFormatted = Math.floor(data.metrics.pageViews).toLocaleString()
  const sessionDurationFormatted = formatSeconds(data.metrics.sessionDuration)

  return (
    <MetricCard
      title="Page Views"
      value={pageViewsFormatted}  // ← From API
      trend={Math.round(data.metrics.pageViewsTrend)}
      // ...
    />
  )
}

πŸ“ Implementation Steps

Step 1: Import the Hook

import { useDashboardData } from "@/hooks/useDashboardData";

Step 2: Use the Hook in Component

const { data, loading, error } = useDashboardData(dateRange);

Step 3: Add Loading State

if (loading) {
  return (
    <div className="flex items-center justify-center min-h-screen">
      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" />
    </div>
  )
}

Step 4: Add Error Handling

if (error) {
  return (
    <div className="bg-destructive/10 border border-destructive rounded-lg p-4">
      <p className="text-destructive font-medium">Error loading dashboard</p>
      <p className="text-sm text-destructive/80">{error}</p>
    </div>
  )
}

Step 5: Replace Mock Data with Real Data

// Before
<MetricCard value="45,231" />

// After
<MetricCard value={Math.floor(data.metrics.pageViews).toLocaleString()} />

πŸ” Authentication

All dashboard endpoints require authentication. The hooks automatically:

  1. Get token from localStorage.getItem('accessToken')
  2. Send it in the Authorization: Bearer {token} header
  3. Fail gracefully if no token exists

Make sure users are logged in before viewing dashboard!


πŸ“Š Data Flow Example

User wants to see Page Views metric:

1. Dashboard component renders
2. useDashboardData("7d") hook is called
3. Hook checks for token in localStorage
4. Hook makes GET request to /api/v1/dashboard/all
5. Request includes: Authorization: Bearer {token}
6. Backend receives request
7. Backend authenticates user via authMiddleware
8. Backend queries database for metrics
9. Backend returns JSON with data
10. Hook updates state with data
11. Component re-renders with real metrics
12. User sees actual data

πŸ§ͺ Testing the Integration

1. Start Backend

npm run build
npm run start

2. Login to Get Token

# Register or login to get access token
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"testuser@example.com","password":"SecurePass123"}'

# Copy the accessToken from response

3. Test API Directly

curl http://localhost:3000/api/v1/dashboard/metrics \
  -H "Authorization: Bearer YOUR_TOKEN"

Should return:

{
  "pageViews": 45231,
  "uniqueVisitors": 12847,
  "sessionDuration": 222,
  "bounceRate": 32.4,
  "pageViewsTrend": 12,
  ...
}

4. Test in Dashboard

npm run dev

Navigate to /dashboard - should display real data from API.


πŸ“ˆ Response Examples

Metrics Response

{
  "pageViews": 45231,
  "uniqueVisitors": 12847,
  "sessionDuration": 222,
  "bounceRate": 32.4,
  "pageViewsTrend": 12,
  "visitorsTrend": 8,
  "sessionDurationTrend": -2,
  "bounceRateTrend": 5
}

Chart Data Response

{
  "pageViewsChart": {
    "data": [
      { "date": "2026-01-22", "value": 4523 },
      { "date": "2026-01-23", "value": 5231 },
      { "date": "2026-01-24", "value": 4891 },
      ...
    ]
  },
  "visitorsChart": {
    "data": [
      { "date": "2026-01-22", "value": 1234 },
      { "date": "2026-01-23", "value": 1456 },
      ...
    ]
  }
}

🎯 Next Steps

  1. Modify Dashboard.tsx to use hooks
  2. Add loading skeleton component
  3. Add error boundary for better error handling
  4. Test with real token from login
  5. Seed database with real test data
  6. Deploy to production

πŸ’‘ Best Practices

βœ… DO

❌ DON’T


πŸš€ Performance Optimization (Future)


πŸ“ž Troubleshooting

β€œNot authenticated” error

Problem: Getting 401 Unauthorized Solution: Make sure user is logged in. Token might be expired.

Empty data response

Problem: Dashboard shows no data Solution: Backend might be returning null. Check:

Network error

Problem: Can’t reach API Solution: Make sure backend is running on port 3000

CORS error

Problem: Cross-origin request blocked Solution: CORS middleware is already configured. Check browser console.



Ready to integrate? Follow the implementation steps above! πŸš€