Overview
This guide provides step-by-step instructions to implement chat persistence using Firebase Firestore within a Next.js application powered by the Thesys C1 GenUI SDK. By following this guide, you’ll learn how to store, retrieve, and manage chat threads and messages, enabling a seamless user experience across sessions. The complete code for the example referenced in this guide can be found in the Thesys examples repository.Implementation Steps
1
Set up Firebase Project & SDK
First, ensure your Firebase project is ready and the Firebase SDK is configured in your Next.js application.
- Go to the Firebase Console,and copy the
firebaseConfigobject.
-
Update Firebase Config File (
src/firebaseConfig.ts): Replace the placeholder values infirebaseConfigwith your actual credentials insrc/firebaseConfig.ts:src/firebaseConfig.ts
2
Create Thread Service for Firebase
Implement a service layer that handles persistence logic using Firestore.Create
src/services/threadService.ts:1. Core CRUD Functions:
Implement functions to create, read, update, and delete threads and messages.Refer to the complete example threadService.ts for full implementations of others like getThreadList, getUIThreadMessages, getLLMThreadMessages, updateMessage, deleteThread, and updateThread similarly.createThread
createThread
src/services/threadService.ts (createThread)
addMessages
addMessages
src/services/threadService.ts (addMessages)
3
Integrate Service with Frontend
Configure C1Chat component (
src/app/page.tsx) to use the functions in threadService.ts for data operations.-
Configure C1 SDK Hooks:
Pass the
threadServicefunctions to theuseThreadListManageranduseThreadManagerhooks.See the complete examplesrc/app/page.tsx (Hook Configuration)page.tsxfor detailed hook setup with imports.
4
Add Backend Chat API Route
Add Chat Api route to use Thesys C1 Api along with functions in
threadService.ts for fetching historical messages and saving new ones.-
Fetch History for LLM:
Before calling the LLM, fetch the existing messages for the thread using
getLLMThreadMessages.src/app/api/chat/route.ts (Fetch History) -
Save Messages on Stream End:
In the
on("end")event of the LLM stream, useaddMessagesto store the new user prompt and all assistant/tool messages generated in that turn.Refer to the complete examplesrc/app/api/chat/route.ts (Save Messages)/api/chat/route.tsfor context.
Running and Testing
- Ensure your Firebase credentials are correctly set in
src/firebaseConfig.ts. - Ensure your
THESYS_API_KEYis set in.env. - Run
npm run dev. - Test creating new chats, sending messages, switching between chats, and refreshing the page to see if history persists. Check the Firebase console to see data being written to Firestore.
