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.
Here are the detailed step-by-step instructions on how to setup the database and fetch the firebase configuration:
Create Firestore Database:
Create a new project or use an existing one in the Firebase Console.
Navigate to “Firestore Database” and click “Create database”.
Choose to start in Test mode for easier setup for the demo. This allows open read/write access for about 30 days.
Important: Test mode rules are insecure and should not be used in a production environment.
Get Firebase Configuration:
In your Firebase project, go to “Project settings” (gear icon) > “General” tab.
Under “Your apps”, click “Add app” and select the Web platform (</>).
Register your app and Firebase will provide a firebaseConfig object. Copy this object.
Update Firebase Config File (src/firebaseConfig.ts):
Replace the placeholder values in firebaseConfig with your actual credentials in src/firebaseConfig.ts:
src/firebaseConfig.ts
Copy
Ask AI
import { initializeApp, getApp, getApps } from "firebase/app";import { getFirestore } from "firebase/firestore";// IMPORTANT: Replace these with your actual Firebase project configuration!const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID", measurementId: "YOUR_MEASUREMENT_ID"};// Initialize Firebaselet app;if (!getApps().length) { app = initializeApp(firebaseConfig);} else { app = getApp();}const db = getFirestore(app);export { db };
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.
Save Messages on Stream End:
In the on("end") event of the LLM stream, use addMessages to store the new user prompt and all assistant/tool messages generated in that turn.
src/app/api/chat/route.ts (Save Messages)
Copy
Ask AI
runToolsResponse.on("end", async () => { if (isError) { return; } const runToolsMessagesWithId = allRunToolsMessages.map((m, index) => { const id = allRunToolsMessages.length - 1 === index // for last message (the response shown to user), use the responseId as provided by the UI ? responseId : crypto.randomUUID(); return { ...m, id, }; }); const messagesToStore = [prompt, ...runToolsMessagesWithId]; await addMessages(threadId, ...messagesToStore);});
Ensure your Firebase credentials are correctly set in src/firebaseConfig.ts.
Ensure your THESYS_API_KEY is 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.
By following this guide, you’ve integrated Firebase Firestore for robust chat persistence in your conversational application.
This setup provides a scalable backend for your chat data, enhancing user experience by preserving conversation history.
Assistant
Responses are generated using AI and may contain mistakes.