We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Learn More
contact@techquestworld.com
+919547614783
Premium Article
Published 5 months ago

How to Build an AI Chatbot Using Node.js & OpenAI API (ChatGPT-4)

5 min read
603 views
How to Build an AI Chatbot Using Node.js & OpenAI API (ChatGPT-4)
Photo by Techquestworld

Learn how to build a fully functional AI chatbot using Node.js and OpenAI's ChatGPT-4 API. This guide covers everything from scratch for beginners and dives into advanced features.

Introduction


In this project, we will:


Set up a Node.js project


Connect with the OpenAI ChatGPT-4 API


Create an interactive chatbot interface


Add context-aware conversation


Deploy it to a cloud server

Step 1: Prerequisites


Node.js (v18+ recommended)


Create OpenAI account for API access


Basic knowledge of JavaScript


Install Node:

https://nodejs.org/en

Step 2: Initialize Project


> mkdir ai-chatbot

> cd ai-chatbot

> npm init -y

> npm install express axios dotenv cors


Create the following file structure:


ai-chatbot/

|-- index.js

|-- .env

|-- public/

|-- index.html

Step 3: Set Up OpenAI API Key


Create a .env file:


OPENAI_API_KEY=your-openai-api-key-here

Step 4: Create Express Server

require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cors());
app.use(express.static('public'));

app.post('/chat', async (req, res) => {
const userMessage = req.body.message;
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful chatbot.' },
{ role: 'user', content: userMessage }
]
},
{
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
res.json({ reply: response.data.choices[0].message.content });
} catch (error) {
res.status(500).json({ error: 'Something went wrong' });
}
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Step 5: Create Frontend UI

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot - TechQuestWorld</title>
</head>
<body>
<h2>AI Chatbot</h2>
<input type="text" id="message" placeholder="Ask me something...">
<button onclick="sendMessage()">Send</button>
<div id="chat"></div>

<script>
async function sendMessage() {
const msg = document.getElementById('message').value;
const res = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
});
const data = await res.json();
document.getElementById('chat').innerHTML += `<p><b>You:</b> ${msg}</p>`;
document.getElementById('chat').innerHTML += `<p><b>Bot:</b> ${data.reply}</p>`;
}
</script>
</body>
</html>

Step 6: Run Your Bot


node index.js


Visit: http://localhost:3000

Step 7: Deployment


Deploy chatbot using platforms like:


Render (https://render.com/)


Railway (https://railway.app/)


Vercel (for frontend only)



Use Procfile and update .env in server settings.

Congratulations! You've just built a powerful AI chatbot using Node.js and the OpenAI API—step by step from scratch. Whether you're aiming to integrate this bot into a web app, customer service system or just experimenting, you now have a solid foundation to build on.

Keep building. Keep learning. TechQuestWorld is with you.

Author
TAPAS SAHOO

Developer by Profession, Techie by Heart

A curious mind with a love for writing and technology, dedicated to simplifying web development and programming topics while keeping up with the ever-changing tech landscape.

Discussion (0)

Replying to
Previous Article
How to Use React Helmet for Dynamic Page Titl...

Boost your React app's SEO and user experience with React Helmet. This post covers step-by-step usag...

Next Article
Build a GPT-4 AI Chatbot with Node.js – Full...

Learn how to build a powerful AI chatbot using Node.js and OpenAI GPT-4 API. This tutorial includes...

Related Articles

Laravel vs NodeJS in 2025: Which One Should You Learn First?
Laravel vs NodeJS in 2025: Which One Should You Le...

Laravel or NodeJS – which one should you learn in 2025? This guide helps you choose the right backen...

Node.js Async vs Await Explained with Real Examples
Node.js Async vs Await Explained with Real Example...

Master async and await in Node.js with this easy guide. Includes real code examples, pros/cons and p...

ExpressJS vs NestJS: Which Node.js Framework Should You Choose in 2025?
ExpressJS vs NestJS: Which Node.js Framework Shoul...

Discover the core differences between ExpressJS and NestJS. Whether you build APIs or full-scale app...

Build Your Own Cron Job Manager in Node.js | Beginner-Friendly Guide
Build Your Own Cron Job Manager in Node.js | Begin...

Learn how to create your own custom Cron Job Manager in Node.js using just one simple method. Automa...