Devlopr

How to Build an AI Chatbot Using OpenAI and Node.js

Kranthi Swaroop
Kranthi Swaroop
Web developer
Published on July 28, 2025

AI chatbots are no longer futuristic tools. With APIs like OpenAI's GPT models, building your own chatbot is surprisingly doable. In this guide, you'll learn how to create a basic AI chatbot using Node.js and the OpenAI API.

We’ll walk through setting up a Node.js project, integrating OpenAI, and building a simple backend that accepts user input and responds like ChatGPT.

What You’ll Need

  • Basic knowledge of JavaScript and Node.js
  • An OpenAI account and API key
  • Node.js installed on your computer
  • A text editor (VS Code recommended)
  • Optional: Postman or curl for testing the endpoint

Step 1: Set Up a New Node.js Project

Start by creating a new folder for your chatbot and initialize it as a Node project.

mkdir ai-chatbot
cd ai-chatbot
npm init -y

This will create a package.json file.

Step 2: Install Required Packages

You’ll need the following NPM packages:

  • express – For handling HTTP requests
  • dotenv – To manage your OpenAI key safely
  • openai – The official OpenAI Node.js SDK
npm install express dotenv openai

Step 3: Get Your OpenAI API Key

Go to OpenAI’s API key page, log in, and generate a secret key.

Create a new file in your project root called .env and add your key like this:

OPENAI_API_KEY=your_secret_key_here

Make sure to add .env to your .gitignore so it never gets pushed to GitHub.

Step 4: Build the Express Server

Now let’s build a simple Express server that can accept chat messages and reply with AI-generated responses.

Create a file called server.js:
require('dotenv').config()
const express = require('express')
const { OpenAI } = require('openai')

const app = express()
const port = 3000

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
})

app.use(express.json())

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

  if (!message) {
    return res.status(400).json({ error: 'Message is required' })
  }

  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [
        { role: 'system', content: 'You are a helpful assistant.' },
        { role: 'user', content: message }
      ]
    })

    const reply = response.choices[0].message.content
    res.json({ reply })
  } catch (err) {
    console.error(err)
    res.status(500).json({ error: 'Failed to fetch reply from OpenAI' })
  }
})

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`)
})

Step 5: Test Your Chatbot

You can now run your server:

node server.js

To test it, you can use curl:

curl -X POST http://localhost:3000/chat \
  -H "Content-Type: application/json" \
  -d '{"message":"What is the capital of France?"}'

Or use Postman with a POST request to /chat and a JSON body:

{
  "message": "Tell me a joke."
}

How the Messages Array Works

The messages array tells the AI how the conversation flows. You can pass:

  • system – Initial instruction to set the bot’s behavior
  • user – The user’s input
  • assistant – Past replies (optional)

Example:

messages: [
  { role: "system", content: "You are a coding tutor." },
  { role: "user", content: "Explain closures in JavaScript." }
]

This helps shape how the model responds — in this case, like a tutor.

Optional: Add Conversation Memory

Right now, the chatbot only sees the latest message. If you want it to remember previous messages, you can keep track of the full message history.

Example in-memory version:
let chatHistory = [
  { role: "system", content: "You are a helpful assistant." }
]

app.post('/chat', async (req, res) => {
  const { message } = req.body
  chatHistory.push({ role: "user", content: message })

  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: chatHistory
  })

  const reply = response.choices[0].message.content
  chatHistory.push({ role: "assistant", content: reply })

  res.json({ reply })
})

This keeps the conversation going, though in a real app, you'd want to manage sessions and store history per user.

Common Errors and How to Fix Them

  • 401 Unauthorized – Check if your API key is correct and not expired.
  • 429 Too Many Requests – You’ve hit the rate limit. Slow down your calls.
  • 500 Internal Server Error – OpenAI might be down, or your message formatting is incorrect.

Ideas to Expand the Chatbot

  • Connect it to a frontend using React or plain HTML + JavaScript
  • Add context-specific system prompts (support agent, doctor, storyteller)
  • Store conversation history in a database like MongoDB
  • Add user authentication to create personal bots
  • Deploy the backend to platforms like Render, Vercel, or Railway
Back to Home
HomeExplore