Skip to content

An AI-powered search engine with a generative UI

feat: Add Vercel Analytics tracking for chat events

Yoshiki Miura05b1e98193a1
diff --git a/.env.local.example b/.env.local.example
index bce78d30..48ab5bcc 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -78,9 +78,12 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=[YOUR_SUPABASE_ANON_KEY]
# -----------------------------------------------------------------------------
# Cloud Deployment Configuration
# -----------------------------------------------------------------------------
-# Enable rate limiting for cloud deployments
-# When enabled, quality mode chat requests are limited to 5 per day
-# Requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN to be configured
+# Enable rate limiting and analytics for cloud deployments
+# When enabled:
+# - Quality mode chat requests are limited to 5 per day
+# - Analytics events are tracked to Vercel Analytics (search mode, model type,
+# conversation turns, etc.)
+# Requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for rate limiting
# MORPHIC_CLOUD_DEPLOYMENT=true
# -----------------------------------------------------------------------------
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 67f0f473..11785795 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,6 +1,8 @@
import { revalidateTag } from 'next/cache'
import { cookies } from 'next/headers'
+import { loadChat } from '@/lib/actions/chat'
+import { calculateConversationTurn, trackChatEvent } from '@/lib/analytics'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { checkAndEnforceQualityLimit } from '@/lib/rate-limit/quality-limit'
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
@@ -121,6 +123,39 @@ export async function POST(req: Request) {
perfTime('createChatStreamResponse resolved', streamStart)
+ // Track analytics event (non-blocking)
+ // Calculate conversation turn by loading chat history
+ ;(async () => {
+ try {
+ let conversationTurn = 1 // Default for new chats
+
+ // For existing chats, load history and calculate turn number
+ if (!isNewChat) {
+ const chat = await loadChat(chatId, userId)
+ if (chat?.messages) {
+ // Add 1 to account for the current message being sent
+ conversationTurn = calculateConversationTurn(chat.messages) + 1
+ }
+ }
+
+ await trackChatEvent({
+ searchMode,
+ modelType: modelTypeCookie === 'quality' ? 'quality' : 'speed',
+ conversationTurn,
+ isNewChat: isNewChat ?? false,
+ trigger:
+ (trigger as 'submit-message' | 'regenerate-message') ??
+ 'submit-message',
+ chatId,
+ userId,
+ modelId: selectedModel.id
+ })
+ } catch (error) {
+ // Log error but don't throw - analytics should never break the app
+ console.error('Analytics tracking failed:', error)
+ }
+ })()
+
// Invalidate the cache for this specific chat after creating the response
// This ensures the next load will get fresh data
if (chatId) {
diff --git a/lib/analytics/index.ts b/lib/analytics/index.ts
new file mode 100644
index 00000000..f1d9e393
--- /dev/null
+++ b/lib/analytics/index.ts
@@ -0,0 +1,13 @@
+/**
+ * Analytics module
+ *
+ * Provides a unified interface for tracking analytics events.
+ * Currently uses Vercel Analytics, but designed to be provider-agnostic
+ * for future extensibility.
+ *
+ * @module analytics
+ */
+
+export { trackChatEvent } from './track-chat-event'
+export type { AnalyticsProvider, ChatEventData } from './types'
+export { calculateConversationTurn } from './utils'
diff --git a/lib/analytics/track-chat-event.ts b/lib/analytics/track-chat-event.ts
new file mode 100644
index 00000000..370d7c1b
--- /dev/null
+++ b/lib/analytics/track-chat-event.ts
@@ -0,0 +1,53 @@
+import { track } from '@vercel/analytics/server'
+
+import type { ChatEventData } from './types'
+
+/**
+ * Track a chat event to analytics provider
+ *
+ * Currently uses Vercel Analytics. Only sends events when MORPHIC_CLOUD_DEPLOYMENT=true.
+ * Errors are logged but do not interrupt the application flow.
+ *
+ * Future extensibility: This function can be modified to support multiple providers
+ * by checking an environment variable (e.g., ANALYTICS_PROVIDER) and routing to
+ * the appropriate provider implementation.
+ *
+ * @param data - Chat event data to track
+ *
+ * @example
+ * ```typescript
+ * await trackChatEvent({
+ * searchMode: 'quick',
+ * modelType: 'quality',
+ * conversationTurn: 1,
+ * isNewChat: true,
+ * trigger: 'submit-message',
+ * chatId: 'clx3k2j5m0000qzrmn4y8b9wy',
+ * userId: '550e8400-e29b-41d4-a716-446655440000',
+ * modelId: 'gpt-4'
+ * })
+ * ```
+ */
+export async function trackChatEvent(data: ChatEventData): Promise<void> {
+ // Only track events in cloud deployment environment
+ if (process.env.MORPHIC_CLOUD_DEPLOYMENT !== 'true') {
+ return
+ }
+
+ try {
+ // Send event to Vercel Analytics
+ await track('chat_message_sent', {
+ searchMode: data.searchMode,
+ modelType: data.modelType,
+ conversationTurn: data.conversationTurn,
+ isNewChat: data.isNewChat,
+ trigger: data.trigger,
+ chatId: data.chatId, // CUID2 - safe for tracking
+ userId: data.userId, // Supabase UUID - pseudonymized identifier
+ modelId: data.modelId
+ })
+ } catch (error) {
+ // Log error but don't throw - analytics should never break the app
+ console.error('Failed to track analytics event:', error)
+ }
+}
diff --git a/lib/analytics/types.ts b/lib/analytics/types.ts
new file mode 100644
index 00000000..fa2877c7
--- /dev/null
+++ b/lib/analytics/types.ts
@@ -0,0 +1,42 @@
+/**
+ * Analytics module types
+ *
+ * This module provides type definitions for analytics tracking.
+ * The interfaces are provider-agnostic to allow future extensibility.
+ */
+
+/**
+ * Chat event data structure
+ * Contains all information needed to track a chat interaction
+ */
+export interface ChatEventData {
+ /** Search mode used for the chat */
+ searchMode: 'quick' | 'planning' | 'adaptive'
+ /** Model type preference */
+ modelType: 'speed' | 'quality'
+ /** Conversation turn number (1-indexed, represents follow-up count) */
+ conversationTurn: number
+ /** Whether this is a new chat session */
+ isNewChat: boolean
+ /** Type of trigger that initiated the chat */
+ trigger: 'submit-message' | 'regenerate-message'
+ /** Chat session ID (CUID2 - safe for tracking) */
+ chatId: string
+ /** User ID (Supabase UUID - pseudonymized identifier) */
+ userId: string
+ /** Model identifier used for the chat */
+ modelId: string
+}
+
+/**
+ * Analytics provider interface
+ * Future extensibility point: implement this interface for other providers
+ * (e.g., PostHog, DataBuddy, custom analytics)
+ */
+export interface AnalyticsProvider {
+ /**
+ * Track a chat event
+ * @param data - Chat event data to track
+ */
+ trackChatEvent(data: ChatEventData): Promise<void>
+}
diff --git a/lib/analytics/utils.ts b/lib/analytics/utils.ts
new file mode 100644
index 00000000..b92e7cb9
--- /dev/null
+++ b/lib/analytics/utils.ts
@@ -0,0 +1,25 @@
+import type { UIMessage } from 'ai'
+
+/**
+ * Calculate the conversation turn number from message history
+ *
+ * The turn number represents how many user messages have been sent,
+ * which indicates the follow-up count (1 = initial message, 2+ = follow-ups)
+ *
+ * @param messages - Array of UI messages from the conversation
+ * @returns Turn number (1-indexed)
+ *
+ * @example
+ * ```typescript
+ * const messages = [
+ * { role: 'user', parts: [...] },
+ * { role: 'assistant', parts: [...] },
+ * { role: 'user', parts: [...] }
+ * ]
+ * calculateConversationTurn(messages) // Returns 2
+ * ```
+ */
+export function calculateConversationTurn(messages: UIMessage[]): number {
+ const userMessageCount = messages.filter(msg => msg.role === 'user').length
+ return Math.max(1, userMessageCount)
+}