
Hi, welcome here In this tutorial, we will build a ChatGPT clone using react js as a front-end, and node & express js as a backend. This is the complete tutorial on how to use OpenAI API in node js for text generation. The prerequisites for this project are as follows:
- Node.js should be installed in your system.
- Create a brand new ReactJs project. Just copy the code below:
code to create reactjs project:
npx create-react-app my-app
JavaScriptcode to create nodejs project with express js and required packages:
npm init -y
npm i express body-parser cors morgan openai
JavaScriptThe brand-new React Js project should look like this:

Here is your App.js file, copy the code below and paste it into App.js.
import logo from './logo.svg';
import './App.css';
import { useState } from "react";
import ChatMsg from './components/ChatMsg';
function App() {
const [input, setInput] = useState("")
const [chatLog, setChatLog] = useState(
[{
user: "me",
message: "Hi"
},{
user: "gpt",
message: "How can I help you"
}]
)
function clearButton (){
setChatLog([])
}
async function handleSubmit(e){
e.preventDefault();
let chatLogNew = [...chatLog, {user: "me", message: `${input}`}]
setInput("");
setChatLog(chatLogNew)
// fetching response to the api
const messages = chatLogNew.map((message) => message.message).join("\n")
const response = await fetch("http://localhost:3080/", {
method:"POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message : messages
})
});
const data = await response.json();
setChatLog([...chatLogNew, {user: "gpt", message: `${data.message}`}])
// console.log(data.message);
// console.log("from app");
}
return (
<div className="App">
<aside className="sideBar mainDiv">
<div className="newChatButton">
<span>+ </span>
New chat
</div>
<button onClick={clearButton} className="clearChatButton"><span>? </span>clear conversations</button>
</aside>
<section className="chatBar">
<div className="chat-log">
{chatLog.map((message, index) => (
<ChatMsg key={index} message={message} />
))}
</div>
<div className="chat-input-section">
<form onSubmit={handleSubmit}>
<input className="chat-input-button" value={input} onChange={(e)=> setInput(e.target.value)} autoFocus />
</form>
</div>
</section>
</div>
);
}
export default App;
JavaScriptHere is your code for the App.css file:
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* custome styling */
.App {
text-align: center;
display: flex;
color: rgb(25, 25, 25);
background: rgb(255,255,255);
background: linear-gradient(180deg, rgba(255,255,255,1) 0%, rgb(248, 253, 255) 45%, rgba(255,255,255,1) 100%);
position: absolute;
top:0;
bottom:0;
right:0;
left:0;
}
.sideBar{
width: 240px;
padding: 10px;
color: rgb(230, 230, 230);
background: rgb(28,28,27);
background: linear-gradient(180deg, rgba(28,28,27,1) 0%, rgb(27, 27, 27) 35%, rgb(52, 54, 54) 100%);
}
.mainDiv{
z-index: 1;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: transparent;
/* font-family: Montserrat, Helvetica, Arial, sans-serif; */
font-size: 14px;
line-height: 1.42857143;
list-style: none;
outline: 0;
text-decoration: none;
/* position: relative; */
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
/* border-radius: 3px; */
border: none;
/* padding: 16px 8px; */
box-shadow: 0 15px 30px rgba(32, 36, 39, 0.705);
pointer-events: auto;
cursor: pointer;
transition: all .15s ease-in-out;
}
.chatBar{
flex: 1;
position: relative;
}
.newChatButton{
border: 1px solid rgb(80, 80, 80);
padding: 12px 15px;
border-radius: 5px;
text-align: left;
transition: ease 0.25s all;
}
.newChatButton:hover{
background-color: rgba(255, 255, 255, 0.05);
}
.clearChatButton{
color: rgb(230, 230, 230);
margin-top: 10px;
border: none;
width: 240px;
padding: 12px 15px;
border-radius: 5px;
text-align: left;
transition: ease 0.25s all;
background-color: #202123;
}
.clearChatButton:hover{
background-color: rgba(255, 255, 255, 0.05);
}
.chat-input-section{
position: absolute;
padding: 12px;
left: 0;
right: 0;
bottom: 0;
}
.chat-input-button{
width: 60%;
background-color: rgb(255, 255, 255);
border: 1px solid rgb(228, 228, 228);
border-radius: 5px;
padding: 12px;
font-size: small;
outline: none;
box-shadow: 0px 0px 10px 2px rgb(245, 245, 245);
}
.chat-log{
text-align: left;
}
.chat-message.chatgpt{
background-color: rgb(247, 247, 248);
}
.chat-message-center{
display: flex;
margin-left: auto;
margin-right: auto;
max-width: 440px;
padding: 12px;
padding-left: 24px;
padding-right: 24px;
}
.avatar{
/* width: 60px;
height: 42px; */
border-radius: 50%;
/* background-color: #202123; */
}
.avatar.chatgpt{
display: flex;
align-items: center;
justify-content: center;
/* width: 40px;
height: 40px; */
border-radius: 50%;
/* color: white; */
/* background-color: #0da37f; */
/* background: linear-gradient(90deg, rgb(52, 230, 52), rgb(27, 241, 241)); */
}
.message{
padding: 0px 40px;
}
CSSAfter creating a reactjs project, make a component ‘ChatMsg.js’ and copy the code below, and past it to ‘ChatMsg.js’:
The code for the ‘ChatMsg.js’ is as follows:
import React from 'react'
const ChatMsg = ({ message }) => {
return (
<div className={`chat-message ${message.user === "gpt" && "chatgpt"}`}>
<div className="chat-message-center">
<div className={`avatar ${message.user === "gpt" && "chatgpt"}`}>
</div>
<div className="message">
{message.message}
</div>
</div>
</div>
)
}
export default ChatMsg
JavaScriptThe Node Js folder will contain the index.js file Here is your code for the index.js file, don’t forget to change the organization and apiKey section according to your credentials:
const express = require('express');
const bodyParser = require('body-parser')
const cors = require("cors")
const app = express();
const port = 3080;
const { Configuration, OpenAIApi } = require("openai");
app.use(express.json())
app.use(cors())
const configuration = new Configuration({
organization: "your ganization code",
apiKey: "your api key",
});
const openai = new OpenAIApi(configuration);
// creating a express api
app.post('/', async function(req, res){
const { message } = req.body
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: `${message}`,
max_tokens: 100,
temperature: 0.5,
});
res.json({
message: response.data.choices[0].text
})
})
app.listen(port, function(){
console.log(`The app listen at http://localhost:${port}`);
})
JavaScriptAfter writing the code into the files (don’t forget to save it ?,) you can run the command below:
Enter the code below to start your react js project:
npm run start
JavaScriptEnter the code below to start your node js project:
node index.js
JavaScript