Integrate Chatbase Into Your Next.js App in 30 Minutes
Chatbase lets you build a custom AI chatbot trained on your own content. Learn how to integrate it into a Next.js app with a custom UI and conversation persistence.
What Is Chatbase?
Chatbase is a platform that lets you create AI chatbots trained on your own data — PDFs, websites, text, or structured data. It handles the RAG pipeline, vector storage, and LLM calls. You get an API to query your trained chatbot from any frontend.
Setting Up a Chatbase Bot
After creating an account and training your chatbot on your content (Chatbase handles the embedding and indexing), you'll get a chatbot ID and API key. Your bot is ready to query within minutes of training.
Creating the API Proxy Route
Never expose your Chatbase API key to the client. Proxy requests through your Next.js API:
// app/api/chat/route.ts
export async function POST(request: Request) {
const { messages, conversationId } = await request.json();
const response = await fetch(
`https://www.chatbase.co/api/v1/chat`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CHATBASE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages,
chatbotId: process.env.CHATBASE_BOT_ID,
conversationId, // maintains context across messages
stream: true,
}),
}
);
// Stream the response directly to the client
return new Response(response.body, {
headers: { 'Content-Type': 'text/event-stream' },
});
}
The Chat Widget Component
'use client';
import { useChat } from 'ai/react';
import { useState, useRef, useEffect } from 'react';
export function ChatWidget() {
const [open, setOpen] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: '/api/chat',
initialMessages: [
{
id: 'welcome',
role: 'assistant',
content: 'Hi! I'm here to help. What can I answer for you today?'
}
]
});
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
return (
<>
<button
onClick={() => setOpen(!open)}
className="fixed bottom-6 right-6 w-14 h-14 bg-blue-600 text-white rounded-full shadow-lg flex items-center justify-center"
>
💬
</button>
{open && (
<div className="fixed bottom-24 right-6 w-80 h-96 bg-white rounded-xl shadow-2xl flex flex-col border">
<div className="p-3 border-b bg-blue-600 text-white rounded-t-xl flex justify-between">
<span className="font-semibold">Support Chat</span>
<button onClick={() => setOpen(false)}>✕</button>
</div>
<div className="flex-1 overflow-y-auto p-3 space-y-3">
{messages.map(m => (
<div
key={m.id}
className={`p-2 rounded-lg text-sm max-w-[80%] ${
m.role === 'user'
? 'ml-auto bg-blue-600 text-white'
: 'bg-gray-100 text-gray-800'
}`}
>
{m.content}
</div>
))}
{isLoading && <div className="bg-gray-100 p-2 rounded-lg text-sm animate-pulse">Thinking...</div>}
<div ref={messagesEndRef} />
</div>
<form onSubmit={handleSubmit} className="p-3 border-t flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="Ask anything..."
className="flex-1 p-2 border rounded text-sm"
/>
<button type="submit" className="px-3 py-2 bg-blue-600 text-white rounded text-sm">
Send
</button>
</form>
</div>
)}
</>
);
}
Persisting Conversations
Store conversation IDs in localStorage so returning users resume their conversation:
import { useChat } from 'ai/react';
import { useState } from 'react';
function usePersistentChat() {
const [conversationId] = useState(() => {
return localStorage.getItem('chatConversationId') ||
crypto.randomUUID();
});
useEffect(() => {
localStorage.setItem('chatConversationId', conversationId);
}, [conversationId]);
return useChat({
api: '/api/chat',
body: { conversationId }, // sent with every message
});
}
Result
In under 30 minutes, you have a fully functional AI chatbot trained on your content, with a custom UI that matches your brand. Chatbase handles the hard parts (RAG, vector search, LLM calls) while you focus on the user experience.
Admin
Chatbase
Build AI chatbot cho website trong vài phút. Train trên docs, FAQ, PDF của bạn.
Cal.com
Open source scheduling — tự host booking system, thay thế Calendly. Free & privacy-first.
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!