Building a Stateless Conversational AI Chatbot with Next.js and ChatBotKit SDK
This tutorial will guide you through the process of building a stateless conversational AI chatbot using the Next.js framework and ChatBotKit SDK. You'll learn how to create a complete chat interface with streaming responses and modern React patterns.
What You'll Learn
By completing this tutorial, you will:
- Set up a Next.js project with ChatBotKit SDK integration
- Create an Edge API endpoint for streaming AI responses
- Build a responsive chat interface using ChatBotKit React components
- Implement stateless conversation management
Prerequisites
Before we begin, ensure you have the following:
- Node.js 18 or later and npm installed
- A ChatBotKit account (sign up at chatbotkit.com)
- Your ChatBotKit API secret key (available from your ChatBotKit dashboard under Settings > API Keys)
- Basic knowledge of React and Next.js
- Approximately 30 minutes to complete this tutorial
Environment Setup: Store your ChatBotKit secret key in process.env.CHATBOTKIT_API_SECRET for secure access throughout the application.
Project Structure
In this tutorial, we'll work with three main files:
pages/index.js: Renders the chat user interface with message display and inputpages/api/conversation/complete.js: Edge API endpoint that handles streaming responses.env.local: Environment variables for secure API key storage
Step 1: Setting Up a Next.js Project
Before we start building our chatbot, we first need to set up a new Next.js project. Follow the steps below to do this:
1.1 Install Node.js and npm
First, you need Node.js and npm installed on your system. If you don't have them installed, you can download Node.js and npm from here.
To verify if you have them installed, run the following commands in your terminal:
1.2 Create a New Next.js App
To create a new Next.js application, you can use create-next-app, which sets up everything automatically for you. To create a new Next.js application, open your terminal, navigate to the directory where you want to create your project, and run the following command:
Replace my-chatbot-app with the name of your application. This command will create a new directory with the name of your application, and it will install all the necessary files and dependencies for a new Next.js application.
1.3 Run the Next.js App
Navigate into your new project's directory:
Then, run the following command to start the development server:
If everything is set up correctly, you should be able to see your new Next.js application by opening http://localhost:3000 in your browser.
1.4 Install ChatBotKit SDK
To install the ChatBotKit SDKs, navigate to your project's root directory in your terminal and run the following command:
This installs three key packages:
@chatbotkit/sdk: Core SDK for ChatBotKit API interactions@chatbotkit/next: Next.js-specific utilities for streaming and Edge runtime@chatbotkit/react: React hooks and components for chat UI
1.5 Configure Environment Variables
Create a .env.local file in your project root to store your ChatBotKit API secret:
Replace your_secret_key_here with the actual secret key from your ChatBotKit dashboard.
Security Note: Never commit
.env.localto version control. Next.js automatically excludes it from Git.
With these steps, we have our Next.js application ready. In the next steps, we will create our chatbot.
Step 2: Setting up the API Endpoint
Now we'll create an API endpoint that handles incoming messages and streams AI responses back to the client. This endpoint uses Next.js Edge Runtime for optimal performance and low latency.
Create a file at pages/api/conversation/complete.js with the following code:
How this works:
ChatBotKitinstance: Creates a stateless SDK client that doesn't persist conversation history. Each request is independent.stream()function: Enables streaming responses from the AI model, providing real-time text generationconversation.complete(null, { messages }): Passesnullas the conversation ID (stateless mode) and the message history- Edge Runtime: Uses Next.js Edge Runtime for faster response times and lower latency
Stateless vs Stateful:
In stateless mode, your application manages message history on the client side. This gives you full control over conversation data and simplifies deployment, but requires sending the full conversation context with each request.
Step 3: Creating the Chat UI
Next, we'll create a chat interface to interact with the API endpoint. This will be done in the pages/index.js file.
We'll use the useConversationManager hook from @chatbotkit/react to manage conversation state, and an AutoTextarea component for the user input field:
Component breakdown:
useConversationManagerhook: Manages conversation state, including messages, user input, and submission handlingmessages: Array of conversation messages withid,type, andtexttext/setText: Current input value and setterthinking: Boolean indicating if the AI is generating a responsesubmit: Function to send the current message
AutoTextarea: Auto-resizing textarea component that expands as the user types- Enter key handling: Submits the message when Enter is pressed (without Shift)
Styling options:
This example uses inline styles for simplicity. For production applications, consider using CSS modules, Tailwind CSS, or styled-components for better maintainability and responsive design.
Step 4: Running the Application
To start the development server, run the following command:
Finally, open http://localhost:3000 with your browser to see your chatbot in action.
You should see a minimal chat interface where you can:
- Type a message in the text area
- Press Enter to submit
- See the AI's response stream in real-time
- Continue the conversation with follow-up messages
Troubleshooting
Issue: "Invalid API Secret" error
- Cause: Your ChatBotKit API secret is missing or incorrect
- Solution:
- Verify your
.env.localfile containsCHATBOTKIT_API_SECRET=your_key - Get your API secret from ChatBotKit dashboard > Settings > API Keys
- Restart your development server after updating
.env.local
- Verify your
Issue: "Module not found" errors
- Cause: ChatBotKit packages not installed correctly
- Solution: Run
npm install @chatbotkit/sdk @chatbotkit/next @chatbotkit/reactagain
Issue: Messages not appearing or streaming not working
- Cause: API endpoint not configured for Edge Runtime
- Solution: Ensure
export const config = { runtime: 'edge' }is present in your API file
Issue: "Cannot read property 'messages'" error
- Cause: Request body not being parsed correctly
- Solution: Verify your API endpoint uses
await req.json()to parse the request body
Next Steps
Now that you have a working stateless chatbot, explore these enhancements:
- Add conversation history: Implement persistent storage using ChatBotKit's stateful conversation API
- Customize the AI model: Configure model parameters like temperature, max tokens, and model selection
- Style your chat interface: Use CSS frameworks like Tailwind or build a custom design
- Add bot personality: Configure backstory and instructions to customize the bot's behavior
- Integrate abilities: Add tools and integrations for weather, search, file access, and more
- Deploy to production: Deploy your chatbot to Vercel, Netlify, or your preferred hosting platform
Resources
- ChatBotKit Node SDK on GitHub - Complete example code
- ChatBotKit Documentation - Full API reference and guides
- ChatBotKit React SDK - React components and hooks documentation
Congratulations on building your stateless conversational AI chatbot with Next.js and ChatBotKit SDK! You now have a foundation for creating sophisticated AI-powered applications.