AI-powered chatbots can enhance user experience and automate responses effectively. In this tutorial, you’ll learn how to quickly build a chatbot using React, Vite, and Cohere’s API, with a backend integration using Express. With its simplicity and speed, Vite makes it easy to set up modern JavaScript applications.
This architecture prevents exposing sensitive API keys by routing requests through a server.
Create a new React project using Vite:
npm create vite@latest ai-chatbot -- --template react
cd ai-chatbot
npm install
Start the development server:
npm run dev
Initialize a new Node.js project in the same directory:
mkdir server && cd server
npm init -y
Install the required packages:
npm install express cors dotenv node-fetch
Update package.json file to use the type module
to enable use of native imports:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"node-fetch": "^3.3.2"
}
}
Create a file named server.js
in the server
directory and add the following code:
import 'dotenv/config'
import express from 'express';
import cors from 'cors';
import fetch from 'node-fetch';
const app = express();
const PORT = 5000;
app.use(cors());
app.use(express.json());
app.post('/generate', async (req, res) => {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
try {
const response = await fetch('https://api.cohere.ai/v1/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.COHERE_API_KEY}`,
},
body: JSON.stringify({
model: 'command-xlarge-nightly',
prompt: `User: ${prompt}\nBot:`,
max_tokens: 100,
}),
});
const data = await response.json();
res.json(data.generations[0].text.trim());
} catch (error) {
console.error('Error calling Cohere API:', error);
res.status(500).json({ error: 'Failed to generate response' });
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Create a .env
file in the server
directory:
COHERE_API_KEY=your_cohere_api_key_here
Start the server:
node server.js
Important: Never share your .env
file or commit it to version control. Add .env
to your .gitignore
file.
Update the App.jsx
file with the following code:
import React, { useState } from 'react';
import './App.css';
const App = () => {
const [messages, setMessages] = useState([]);
const [userInput, setUserInput] = useState('');
const [loading, setLoading] = useState(false);
const sendMessage = async () => {
if (!userInput.trim()) return;
const newMessages = [...messages, { sender: 'user', text: userInput }];
setMessages(newMessages);
setUserInput('');
setLoading(true);
try {
const response = await fetch('http://localhost:5000/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: userInput }),
});
const botReply = await response.text();
setMessages([...newMessages, { sender: 'bot', text: botReply }]);
} catch (error) {
console.error('Error fetching bot reply:', error);
setMessages([
...newMessages,
{ sender: 'bot', text: 'Sorry, something went wrong.' },
]);
} finally {
setLoading(false);
}
};
return (
<div className="chat-container">
<div className="chatbox">
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.sender}`}>
{msg.text}
</div>
))}
{loading && <div className="message bot">Typing...</div>}
</div>
<div className="input-container">
<input
type="text"
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
placeholder="Type your message..."
/>
<button onClick={sendMessage}>Send</button>
</div>
</div>
);
};
export default App;
Create a file named App.css
for styling the chatbot interface:
code.chat-container {
font-family: Arial, sans-serif;
max-width: 500px;
margin: 20px auto;
}
.chatbox {
border: 1px solid #ccc;
padding: 10px;
height: 400px;
overflow-y: auto;
border-radius: 5px;
margin-bottom: 10px;
}
.message {
margin: 5px 0;
padding: 10px;
border-radius: 5px;
}
.message.user {
background-color: #d1e7dd;
text-align: right;
}
.message.bot {
background-color: #f8d7da;
text-align: left;
}
.input-container {
display: flex;
}
input {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px 0 0 5px;
}
button {
padding: 10px;
border: 1px solid #ccc;
border-radius: 0 5px 5px 0;
background-color: #007bff;
color: white;
cursor: pointer;
}
Terminal 1:
npm run dev
Terminal 2 (inside server
):
node server.js
You can find the complete source code for this project on GitHub: AI Chatbot with React and Cohere. Feel free to clone it, explore the code, and customize it to your needs!
You’ve built a functional AI-powered chatbot using React, Vite, Cohere and Express. This project can be enhanced with features like:
Start experimenting and happy coding!