Want a hands-on tutorial that shows you exactly how to build a React chatbot powered by OpenAI? Let’s dive in!
🧰 Why Do This?
- Adds real AI interaction capability to your front-end.
- Teaches prompt chaining and handling context.
- Great portfolio piece and learning experience.
🔧 What You’ll Need
- OpenAI API key
- Node.js & npm or yarn
- Create React App or Vite setup
1. Set Up Your React Project
npx create-react-app ai-chatbot
cd ai-chatbot
npm install openai
2. Secure Your API Key
Create .env.local
:
REACT_APP_OPENAI_KEY=your_api_key_here
⚠️ Never commit this file.
3. Create a Simple Backend Proxy
Since we don’t want to expose API keys in the client, create a quick Express server:
npm install express openai dotenv
// server.js
import express from 'express'
import OpenAI from 'openai'
import 'dotenv/config'
const app = express()
app.use(express.json())
const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY })
app.post('/chat', async (req, res) => {
const { messages } = req.body
const resp = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages,
})
res.json({ reply: resp.choices[0].message.content })
})
app.listen(6000, () => console.log('API ready!'))
4. Connect Front‑end Chat UI
In src/App.js
:
import React, { useState } from 'react'
function App() {
const [msg, setMsg] = useState('')
const [history, setHistory] = useState([])
const sendMsg = async () => {
const userMsg = { role: 'user', content: msg }
const updated = [...history, userMsg]
setHistory(updated)
setMsg('')
const resp = await fetch('/chat', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({ messages: updated })
}).then(r => r.json())
setHistory([...updated, { role: 'assistant', content: resp.reply }])
}
return (
<div>
{history.map((m,i) =>
<div key={i} className={m.role}>{m.content}</div>
)}
<input value={msg} onChange={e => setMsg(e.target.value)} />
<button onClick={sendMsg}>Send</button>
</div>
)
}
export default App
5. Improve the UX
- Add a system message for personality
- Show loading state
- Add auto-scroll to the bottom
- Style the chat bubbles
✅ Customizing Tips
- Switch model to gpt-4 if you have access.
- Stream responses for a “typewriter effect” (like this tutorial suggests)
- Consider deploying the Express server with Vercel or Heroku.
👏 What You’ve Built
You now have a chat interface that:
- Takes input from the user
- Sends prompts (with conversation history) to OpenAI
- Receives and displays AI responses
All in a modern React app with clean separation of front/back-end logic.
🚀 What’s Next?
- Add message persistence (localStorage or a DB)
- Improve accessibility and UX
- Integrate with React frameworks like Next.js
- Deploy your chatbot and show it off!
Top comments (0)