Mongolytics Logo

Mongolytics

Dashboard Setup Guide

Learn how to set up and customize the Mongolytics analytics dashboard to visualize your website traffic data. This guide covers both the pre-built dashboard component and custom dashboard implementations.


Prerequisites

Before setting up the dashboard, ensure you have completed the basic Mongolytics installation. If you haven't done so yet, follow the Installation Guide first.

Step 1: Verify Package Installation

Make sure you have the latest version of Mongolytics installed that includes dashboard components:

npm install @clipper-dev/mongolytics-next

Step 2: Configure Environment Variables

The dashboard uses the same environment variables as the tracking component. Ensure these are set in your .env.local file:

/.env.local

# .env.local
MONGOLYTICS_URI="your-mongodb-atlas-connection-string"
MONGOLYTICS_DB_NAME="your-analytics-database-name"

Optional: Customize the collection name if needed:

/.env.local

# .env.local
MONGOLYTICS_COLLECTION_SESSIONS="mongolytics-sessions"

Step 3: Create the Dashboard API Endpoint

The dashboard needs a dedicated API endpoint to fetch analytics data. This endpoint is separate from the tracking endpoint for security and performance reasons.

For App Router (Recommended)

Create a new file at app/api/mongolytics/dashboard/route.ts:

/app/api/mongolytics/dashboard/route.ts

// app/api/mongolytics/dashboard/route.ts
import { mongolyticsDashboardAppRouteHandler as GET } from '@clipper-dev/mongolytics-next/server';
export { GET };

For Pages Router

Create a new file at pages/api/mongolytics-dashboard.ts:

/pages/api/mongolytics-dashboard.ts

// pages/api/mongolytics-dashboard.ts
import { mongolyticsDashboardPagesRouterHandler } from '@clipper-dev/mongolytics-next/server';
export default mongolyticsDashboardPagesRouterHandler;

Step 4: Add the Dashboard Component

Now you can add the pre-built dashboard component to any page in your application. We recommend creating a dedicated analytics page.

For App Router (Recommended)

Create a new page for your analytics dashboard:

/app/dashboard/analytics/page.tsx

// app/dashboard/analytics/page.tsx
import { MongolyticsDashboard } from '@clipper-dev/mongolytics-next/dashboard';

export default function AnalyticsPage() {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">Analytics Dashboard</h1>
      <MongolyticsDashboard />
    </div>
  );
}

For Pages Router

Create a new page and include the routerType prop:

/pages/dashboard/analytics.tsx

// pages/dashboard/analytics.tsx
import { MongolyticsDashboard } from '@clipper-dev/mongolytics-next/dashboard';

export default function AnalyticsPage() {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">Analytics Dashboard</h1>
      <MongolyticsDashboard routerType="pages" />
    </div>
  );
}

Step 5: Customizing the Dashboard (Optional)

If you want to build a custom dashboard with your own design, you can use the getAnalyticsData function directly:

Custom Dashboard Implementation

// lib/analytics.ts
import { getAnalyticsData } from '@clipper-dev/mongolytics-next/server';

export async function fetchDashboardData() {
  const data = await getAnalyticsData();
  return data;
}

// app/dashboard/custom/page.tsx
import { fetchDashboardData } from '@/lib/analytics';

export default async function CustomDashboard() {
  const { totalSessions, totalPageviews, topPages } = await fetchDashboardData();
  
  return (
    <div className="grid gap-4">
      <div className="stats shadow">
        <div className="stat">
          <div className="stat-title">Total Sessions</div>
          <div className="stat-value">{totalSessions}</div>
        </div>
        <div className="stat">
          <div className="stat-title">Total Page Views</div>
          <div className="stat-value">{totalPageviews}</div>
        </div>
      </div>
      
      <div className="card bg-base-100 shadow">
        <div className="card-body">
          <h2 className="card-title">Top Pages</h2>
          <ul className="space-y-2">
            {topPages.map((page) => (
              <li key={page.path} className="flex justify-between">
                <span>{page.path}</span>
                <span className="badge">{page.count} views</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
}

Step 6: Protecting Your Dashboard (Recommended)

Since analytics data can be sensitive, we strongly recommend protecting your dashboard route with authentication. Here's an example using Next.js middleware:

/middleware.ts

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // Protect the analytics dashboard route
  if (request.nextUrl.pathname.startsWith('/dashboard/analytics')) {
    const authToken = request.cookies.get('auth-token');
    
    // Replace with your actual authentication logic
    if (!authToken || !isValidToken(authToken.value)) {
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }
  
  return NextResponse.next();
}

export const config = {
  matcher: '/dashboard/:path*',
};

Dashboard Features

The pre-built dashboard component includes the following features:

  • Total Sessions: Number of unique visitor sessions
  • Total Page Views: Cumulative count of all page visits
  • Top Pages: Most visited pages with view counts
  • Real-time Updates: Auto-refreshes every 30 seconds
  • Responsive Design: Works on all screen sizes
  • Dark Mode Support: Automatically adapts to your theme

Data Structure

The dashboard API returns the following data structure:

interface AnalyticsData {
  totalSessions: number;
  totalPageviews: number;
  topPages: PageStat[];
}

interface PageStat {
  path: string;
  count: number;
}

Customization Options

The MongolyticsDashboard component accepts several props for customization:

  • refreshInterval - Update frequency in milliseconds (default: 30000)
  • showRealtime - Show real-time indicator (default: true)
  • className - Custom CSS classes for styling
  • routerType - Required for Pages Router ("pages")

Troubleshooting

Dashboard shows no data

- Ensure tracking is properly set up and data exists in MongoDB
- Check that environment variables are correctly configured
- Verify the API endpoint is accessible at /api/mongolytics/dashboard

Authentication issues

- Ensure your middleware is correctly configured
- Check that authentication cookies/tokens are properly set
- Verify the dashboard route matches your middleware matcher

Styling conflicts

- The dashboard uses Tailwind CSS classes by default
- Use the className prop to override default styles
- Consider wrapping in a container with isolated styles if needed

Next Steps

Congratulations! Your analytics dashboard is now set up. You can:

  • Customize the dashboard appearance to match your brand
  • Add additional metrics and visualizations
  • Set up alerts for traffic anomalies
  • Export data for further analysis

For more advanced features and API documentation, check out the API Reference.