A Step-by-Step Guide to Integrate ChatGPT with Vanilla JS & Node.js
Before you begin, make sure you have the following options installed.
Node.js and npm - You can download the latest stable version from the official Node.js website (https://nodejs.org).
Run the following command to setup back-end-server
mkdir chatbot app
cd chatbot-app
npm init -y
We will need a few libraries to handle the server and front end. Use npm to install the necessary dependencies:
npm install express body-parser
Create a new file named server.js in the root directory of your project. This file will handle the communication with the ChatGPT API and serve the frontend files. Add the following code to server.js:
const express = require('express'); const bodyParser = require('body-parser'); const axios = require('axios'); const app = express(); const port = 3000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // API endpoint for processing user messages app.post('/api/chat', async (req, res) => { try { const { message } = req.body; const apiKey = 'YOUR_OPENAI_API_KEY'; const apiUrl = 'https://api.openai.com/v1/engines/davinci-codex/completions'; // Send user message to ChatGPT API const response = await axios.post(apiUrl, { prompt: message, max_tokens: 150, }, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, }, }); // Extract and send the response from ChatGPT back to the frontend res.status(200).json({ reply: response.data.choices[0].text.trim() }); } catch (error) { console.log("🚀 ~ file: index.js:39 ~ app.post ~ error:", error) console.error('Error:', error.message); res.status(500).json({ error: 'Something went wrong' }); } }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); Within the project directory for the front end, create another directory named client. This directory contains our front-end HTML, CSS, and JavaScript files. Create a new file called index.html inside the public directory and add the following HTML structure.
ChatGPT Integration Create a new file named app.js in the public directory and add the following JavaScript code
document.addEventListener('DOMContentLoaded', () => { const messagesContainer = document.getElementById('messages'); const userInput = document.getElementById('userInput'); const addMessage = (text, sender) => { const messageElem = document.createElement('div'); messageElem.classList.add('message'); messageElem.classList.add(sender); messageElem.textContent = text; messagesContainer.appendChild(messageElem); messagesContainer.scrollTop = messagesContainer.scrollHeight; }; const fetchMessageFromChatGpt = async (message) => { try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message }), }); const data = await response.json(); addMessage(data.reply, 'server'); } catch (error) { console.error('Error:', error.message); addMessage('Something went wrong', 'server'); } }; userInput.addEventListener('keypress', (event) => { if (event.key === 'Enter') { const message = userInput.value.trim(); if (message !== '') { addMessage(message, 'user'); userInput.value = ''; fetchMessageFromChatGpt(message); } } }); }); You can add CSS styles to the index.html file to make the chat interface visually appealing or create a separate CSS file and link to the head section of the HTML
Before running the application you must obtain the API key from OpenAI. Visit the OpenAI website (https://beta.openai.com/signup/) to register and get your API key.
Run the following command on your terminal to run the Backend Server. In the server.js directory
node server.js
In this blog, we went through the process of integrating ChatGPT into a web application using Vanilla JavaScript for the front-end and Node.js for the back-end. By following the steps outlined here, you have created a chatbot that can effectively engage in natural language conversations with users. From here, you can further enhance the chatbot by tweaking the UI, adding user credibility, and expanding the types of interactions it can handle. Happy coding!