Skip to content

An AI-powered search engine with a generative UI

feat: Integrate Supabase user ID with chat history

Yoshiki Miuraf51f35c04a73
diff --git a/app/api/chat/[id]/route.ts b/app/api/chat/[id]/route.ts
index a5d3709b..32757fb7 100644
--- a/app/api/chat/[id]/route.ts
+++ b/app/api/chat/[id]/route.ts
@@ -1,4 +1,5 @@
import { deleteChat } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { NextRequest, NextResponse } from 'next/server'
export async function DELETE(
@@ -18,8 +19,7 @@ export async function DELETE(
return NextResponse.json({ error: 'Chat ID is required' }, { status: 400 })
}
- // Replace 'anonymous' with your actual user ID logic if needed
- const userId = 'anonymous'
+ const userId = await getCurrentUserId()
try {
const result = await deleteChat(chatId, userId)
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 478f8c72..906379e3 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,3 +1,4 @@
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { createManualToolStreamResponse } from '@/lib/streaming/create-manual-tool-stream'
import { createToolCallingStreamResponse } from '@/lib/streaming/create-tool-calling-stream'
import { Model } from '@/lib/types/models'
@@ -20,6 +21,7 @@ export async function POST(req: Request) {
const { messages, id: chatId } = await req.json()
const referer = req.headers.get('referer')
const isSharePage = referer?.includes('/share/')
+ const userId = await getCurrentUserId()
if (isSharePage) {
return new Response('Chat API is not available on share pages', {
@@ -62,13 +64,15 @@ export async function POST(req: Request) {
messages,
model: selectedModel,
chatId,
- searchMode
+ searchMode,
+ userId
})
: createManualToolStreamResponse({
messages,
model: selectedModel,
chatId,
- searchMode
+ searchMode,
+ userId
})
} catch (error) {
console.error('API route error:', error)
diff --git a/app/api/chats/route.ts b/app/api/chats/route.ts
index b935981d..ad22a528 100644
--- a/app/api/chats/route.ts
+++ b/app/api/chats/route.ts
@@ -1,4 +1,5 @@
import { getChatsPage } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { type Chat } from '@/lib/types'
import { NextRequest, NextResponse } from 'next/server'
@@ -17,8 +18,7 @@ export async function GET(request: NextRequest) {
const offset = parseInt(searchParams.get('offset') || '0', 10)
const limit = parseInt(searchParams.get('limit') || '20', 10)
- // Replace 'anonymous' with your actual user ID logic
- const userId = 'anonymous'
+ const userId = await getCurrentUserId()
try {
const result = await getChatsPage(userId, limit, offset)
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index 7244c20d..a196eb8c 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -1,5 +1,6 @@
import { Chat } from '@/components/chat'
import { getChat } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { getModels } from '@/lib/config/models'
import { convertToUIMessages } from '@/lib/utils'
import { notFound, redirect } from 'next/navigation'
@@ -10,7 +11,8 @@ export async function generateMetadata(props: {
params: Promise<{ id: string }>
}) {
const { id } = await props.params
- const chat = await getChat(id, 'anonymous')
+ const userId = await getCurrentUserId()
+ const chat = await getChat(id, userId)
return {
title: chat?.title.toString().slice(0, 50) || 'Search'
}
@@ -19,7 +21,7 @@ export async function generateMetadata(props: {
export default async function SearchPage(props: {
params: Promise<{ id: string }>
}) {
- const userId = 'anonymous'
+ const userId = await getCurrentUserId()
const { id } = await props.params
const chat = await getChat(id, userId)
@@ -30,7 +32,7 @@ export default async function SearchPage(props: {
redirect('/')
}
- if (chat?.userId !== userId) {
+ if (chat?.userId !== userId && chat?.userId !== 'anonymous') {
notFound()
}
diff --git a/components/sidebar/chat-history-section.tsx b/components/sidebar/chat-history-section.tsx
index a3a6a317..37d01833 100644
--- a/components/sidebar/chat-history-section.tsx
+++ b/components/sidebar/chat-history-section.tsx
@@ -1,5 +1,6 @@
import { SidebarGroup, SidebarGroupLabel } from '@/components/ui/sidebar'
import { getChatsPage } from '@/lib/actions/chat'
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { ChatHistoryClient } from './chat-history-client'
import { ClearHistoryAction } from './clear-history-action'
@@ -10,8 +11,8 @@ export async function ChatHistorySection() {
}
// Fetch the initial page of chats
- // Replace 'anonymous' with your actual user ID logic
- const { chats, nextOffset } = await getChatsPage('anonymous', 20, 0)
+ const userId = await getCurrentUserId()
+ const { chats, nextOffset } = await getChatsPage(userId, 20, 0)
return (
<div className="flex flex-col flex-1 h-full">
diff --git a/lib/auth/get-current-user.ts b/lib/auth/get-current-user.ts
new file mode 100644
index 00000000..16547ae1
--- /dev/null
+++ b/lib/auth/get-current-user.ts
@@ -0,0 +1,12 @@
+import { createClient } from '@/lib/supabase/server'
+
+export async function getCurrentUser() {
+ const supabase = await createClient()
+ const { data } = await supabase.auth.getUser()
+ return data.user ?? null
+}
+
+export async function getCurrentUserId() {
+ const user = await getCurrentUser()
+ return user?.id ?? 'anonymous'
+}
diff --git a/lib/streaming/create-manual-tool-stream.ts b/lib/streaming/create-manual-tool-stream.ts
index 0e656b77..6a59be08 100644
--- a/lib/streaming/create-manual-tool-stream.ts
+++ b/lib/streaming/create-manual-tool-stream.ts
@@ -15,7 +15,7 @@ import { BaseStreamConfig } from './types'
export function createManualToolStreamResponse(config: BaseStreamConfig) {
return createDataStreamResponse({
execute: async (dataStream: DataStreamWriter) => {
- const { messages, model, chatId, searchMode } = config
+ const { messages, model, chatId, searchMode, userId } = config
const modelId = `${model.providerId}:${model.id}`
let toolCallModelId = model.toolCallModel
? `${model.providerId}:${model.toolCallModel}`
@@ -69,6 +69,7 @@ export function createManualToolStreamResponse(config: BaseStreamConfig) {
model: modelId,
chatId,
dataStream,
+ userId,
skipRelatedQuestions: true,
annotations
})
diff --git a/lib/streaming/create-tool-calling-stream.ts b/lib/streaming/create-tool-calling-stream.ts
index 4a7f569c..712835f0 100644
--- a/lib/streaming/create-tool-calling-stream.ts
+++ b/lib/streaming/create-tool-calling-stream.ts
@@ -27,7 +27,7 @@ function containsAskQuestionTool(message: CoreMessage) {
export function createToolCallingStreamResponse(config: BaseStreamConfig) {
return createDataStreamResponse({
execute: async (dataStream: DataStreamWriter) => {
- const { messages, model, chatId, searchMode } = config
+ const { messages, model, chatId, searchMode, userId } = config
const modelId = `${model.providerId}:${model.id}`
try {
@@ -62,6 +62,7 @@ export function createToolCallingStreamResponse(config: BaseStreamConfig) {
model: modelId,
chatId,
dataStream,
+ userId,
skipRelatedQuestions: shouldSkipRelatedQuestions
})
}
diff --git a/lib/streaming/handle-stream-finish.ts b/lib/streaming/handle-stream-finish.ts
index 743294d7..52e145e5 100644
--- a/lib/streaming/handle-stream-finish.ts
+++ b/lib/streaming/handle-stream-finish.ts
@@ -10,6 +10,7 @@ interface HandleStreamFinishParams {
model: string
chatId: string
dataStream: DataStreamWriter
+ userId: string
skipRelatedQuestions?: boolean
annotations?: ExtendedCoreMessage[]
}
@@ -20,6 +21,7 @@ export async function handleStreamFinish({
model,
chatId,
dataStream,
+ userId,
skipRelatedQuestions = false,
annotations = []
}: HandleStreamFinishParams) {
@@ -69,20 +71,23 @@ export async function handleStreamFinish({
}
// Get the chat from the database if it exists, otherwise create a new one
- const savedChat = (await getChat(chatId)) ?? {
+ const savedChat = (await getChat(chatId, userId)) ?? {
messages: [],
createdAt: new Date(),
- userId: 'anonymous',
+ userId: userId,
path: `/search/${chatId}`,
title: originalMessages[0].content,
id: chatId
}
// Save chat with complete response and related questions
- await saveChat({
- ...savedChat,
- messages: generatedMessages
- }).catch(error => {
+ await saveChat(
+ {
+ ...savedChat,
+ messages: generatedMessages
+ },
+ userId
+ ).catch(error => {
console.error('Failed to save chat:', error)
throw new Error('Failed to save chat history')
})
diff --git a/lib/streaming/types.ts b/lib/streaming/types.ts
index eed1eb4b..4501235d 100644
--- a/lib/streaming/types.ts
+++ b/lib/streaming/types.ts
@@ -6,4 +6,5 @@ export interface BaseStreamConfig {
model: Model
chatId: string
searchMode: boolean
+ userId: string
}