Build a Chatbot with GPT-4o and React


Build a Chatbot with GPT-4o and React
  • Frontend: React.js (for user interface)
  • Backend: Node.js with Express (for API handling and model access)
  • AI Model: GPT-4o via OpenAI API
  • Hosting Options:
    • React frontend: Vercel, Netlify, GitHub Pages
    • Node backend: Render, Heroku, Railway, AWS Elastic Beanstalk

Step 1: Get Access to OpenAI API

  1. Visit the OpenAI platform: https://platform.openai.com
  2. Sign up or log in to your account.
  3. Navigate to API Keys in your account settings.
  4. Generate a new API key.
  5. Save this key securely. You will use this in your backend server (never expose it to the frontend).

Step 2: Set Up the Backend (Node.js + Express)

1. Create the backend project

mkdir gpt-chatbot-backend
cd gpt-chatbot-backend
npm init -y

2. Install required dependencies

npm install express cors body-parser dotenv openai

3. Create a .env file to store your API key

OPENAI_API_KEY=your_openai_api_key_here

4. Create server.js

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { Configuration, OpenAIApi } = require('openai');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(bodyParser.json());

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

app.post('/chat', async (req, res) => {
try {
const { message, history } = req.body;

const messages = [
...history.map((msg) => ({
role: msg.sender === 'user' ? 'user' : 'assistant',
content: msg.text,
})),
{ role: 'user', content: message },
];

const response = await openai.createChatCompletion({
model: 'gpt-4o',
messages,
});

const reply = response.data.choices[0].message.content;
res.json({ reply });
} catch (error) {
console.error('OpenAI API error:', error);
res.status(500).json({ error: 'Error generating response' });
}
});

app.listen(PORT, () => {
console.log(`Backend server running at http://localhost:${PORT}`);
});

5. Run the backend

node server.js

Step 3: Set Up the React Frontend

1. Create the frontend project

npx create-react-app gpt-chatbot-frontend
cd gpt-chatbot-frontend
npm install axios

2. Create Chatbot.js

import React, { useState } from 'react';
import axios from 'axios';

function Chatbot() {
const [messages, setMessages] = useState([
{ sender: 'bot', text: 'Hello! Ask me anything.' }
]);
const [input, setInput] = useState('');

const sendMessage = async () => {
if (!input.trim()) return;

const newUserMessage = { sender: 'user', text: input };
const updatedMessages = [...messages, newUserMessage];
setMessages(updatedMessages);
setInput('');

try {
const response = await axios.post('http://localhost:5000/chat', {
message: input,
history: messages,
});

const botMessage = { sender: 'bot', text: response.data.reply };
setMessages((prev) => [...prev, botMessage]);
} catch (error) {
console.error('Error communicating with the server:', error);
}
};

return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>GPT-4o Chatbot</h2>
<div
style={{
height: '400px',
overflowY: 'auto',
border: '1px solid #ccc',
padding: '10px',
marginBottom: '10px',
}}
>
{messages.map((msg, idx) => (
<div
key={idx}
style={{
textAlign: msg.sender === 'user' ? 'right' : 'left',
marginBottom: '10px',
}}
>
<strong>{msg.sender === 'user' ? 'You' : 'Bot'}:</strong> {msg.text}
</div>
))}
</div>
<input
type="text"
value={input}
placeholder="Type your message..."
onChange={(e) => setInput(e.target.value)}
style={{ width: '80%', padding: '10px' }}
onKeyDown={(e) => {
if (e.key === 'Enter') sendMessage();
}}
/>
<button onClick={sendMessage} style={{ padding: '10px', marginLeft: '10px' }}>
Send
</button>
</div>
);
}

export default Chatbot;

3. Use Chatbot component in App.js

import React from 'react';
import Chatbot from './Chatbot';

function App() {
return (
<div className="App">
<Chatbot />
</div>
);
}

export default App;

4. Start the frontend server

npm start

Step 4: Test the Chatbot Locally

  1. Ensure the backend server is running on port 5000:
node server.js
  1. Ensure the frontend is running on port 3000:
npm start
  1. Open a browser and visit:
http://localhost:3000
  1. Start chatting with your GPT-4o-powered bot.

Step 5: Deployment (Optional)

React Frontend Deployment

  • Vercel:
    • Connect your GitHub repo to Vercel
    • It will auto-deploy on push
    • Update API URL to point to deployed backend
  • Netlify:
    • Drag and drop your build/ folder
    • Or connect via GitHub

Node.js Backend Deployment

  • Render:
    • Create a new web service
    • Point it to your backend repo
    • Add OPENAI_API_KEY in environment variables
    • Add start script in package.json and optionally a Procfile
  • Heroku:
    • Use the Heroku CLI to deploy
    • Configure your OPENAI_API_KEY in the Heroku dashboard

Additional Enhancements

1. Chat History Context

Maintain a message history array and send it to OpenAI to allow context-aware conversations.

2. Authentication

Add user authentication using JWT or OAuth to personalize chats per user.

3. Database Integration

Store messages in MongoDB, PostgreSQL, or Firebase for persistent chat history.

4. Advanced Features

  • Add typing indicators
  • Support for voice input/output
  • Markdown rendering in bot replies
  • File or image uploads

Best Practices

  • Security: Never expose your OpenAI API key in frontend code. Always use a server proxy.
  • Rate Limiting: Implement limits on message frequency to avoid API overuse or abuse.
  • Error Handling: Provide fallback messages when OpenAI API fails or is unreachable.
  • Scalability: Use message queues or serverless functions for high-traffic apps.

Final Notes

You now have a working chatbot that uses GPT-4o and React. The project is modular and can be easily extended to support advanced features such as database integration, session tracking, and multi-user interactions.

Let me know if you’d like:

  • This project turned into a downloadable zip
  • A GitHub repository with complete code
  • Additional features such as file summarization or multilingual support

Leave a Comment

Your email address will not be published. Required fields are marked *