How to Use ChatGPT API in NodeJS?
Last Updated :
06 May, 2025
ChatGPT is a very powerful chatbot by OpenAI that uses Natural Language Processing to interact like humans. It has become very popular among developers and is being widely used for some of its state-of-the-art features, like understanding and interpreting code, and even generating code based on textual requirements. OpenAI has not only provided its functionality as a chatbot on the website but has also provided an API to help integrate ChatGPT into our applications and projects, using which we can make an HTTP request and utilize the response appropriately.

In this article, we will have a look at the step-by-step procedure to integrate ChatGPT API in the Node.js project.
Using ChatGPT in Node.js Application
Adding ChatGPT functionalities to our large-scale NodeJS Application will make that more efficient for the users. So in this article, we will see step by step implementation of where to retrieve the API key, and how to create a NodeJS application that uses OpenAI API, that will work similarly to ChatGPT, and you can make conversation with ChatGPT using that application. Here are the complete steps for using ChatGPT in NodeJS Application.
1. Creating a Node.js Application
First of all, we will create a directory for the project say, chatgpt-api-nodejs, either using GUI or by pasting the below command in the terminal at the desired location in our machine:
mkdir chatgpt-api-nodejs
Now, change the directory to the newly created folder:
cd chatgpt-api-nodejs
To initialize the node.js project, run the below command which creates a package.json file to keep track of project details
npm init -y
We will use axios
for making HTTP requests and dotenv
for managing environment variables.
npm install axios dotenv
2. Retrieving the OPENAI API Key
To use the API, we need to generate the API keys.
A. For that, go to OpenAI and either sign up or login (if you already have an account).
Create OpenAI accountB. Then click on the API option
Creating ChatGPT API keyC. On the left corner you will see API keys, click on it and it will open API keys section. Click on 'Create new secret key, to crate a new one.
Create new Secret KeysD. Click on the 'Create new secret key' button. It will open up a dialog box asking for the name of the key which is optional. After you are done, click 'Create secret key'.
Create new Secret KeysE. A dialog box will appear displaying your secret key/API key. Copy it and 'done'. Save the key safely and do not share it with anyone.
Create new Secret KeysCreate a new file to create an environment variable for storing the API key
touch .env
In the file, create a variable OPENAI_API_KEY
and replace "YOUR OPEN AI API KEY" with
your API key (keeping the quotes)
OPENAI_API_KEY="YOUR OPEN AI API KEY"
3. Implementing NodeJS Application
Create a javascript file say, index.js, and paste the below code inside it.
JavaScript
require('dotenv').config();
const axios = require('axios');
const API_URL = 'https://api.openai.com/v1/chat/completions';
const API_KEY = process.env.OPENAI_API_KEY;
async function getChatResponse(prompt) {
try {
const response = await axios.post(
API_URL,
{
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
max_tokens: 100,
},
{
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
}
);
return response.data.choices[0].message.content;
} catch (error) {
console.error("Error calling ChatGPT API:", error.response ? error.response.data : error.message);
}
}
(async () => {
const response = await getChatResponse("What is ChatGPT?");
console.log("ChatGPT Response:", response);
})();
4. Run the Application
To run the app, run the below command in terminal
node index.js
The above code takes the input prompt through the command line and prints the response generated by the ChatGPT model.
Output
Similar Reads
How to Use ChatGPT API in Python? ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today.
6 min read
How to Create a Chat App Using socket.io in NodeJS? Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options.What We Are Going to Create?In this article,
5 min read
What is ChatGPT API? ChatGPT is a groundbreaking Natural Language Processing (NLP) tool developed by OpenAI. ChatGPT has advanced significantly since its original release in late 2022, resulting in the creation of an API that allows developers to integrate state-of-the-art model capabilities into their applications. Thr
8 min read
How To Create an App Using ChatGPT In the domain of Artificial Intelligence, generative AI has emerged exponentially in the recent past, and ChatGPT has disrupted the industry completely. ChatGPT is used to generate plagiarism-free content for learning and knowledgeful purposes. But you can also create software applications using it.
9 min read
How to Setup a Modern React Chatbot Integrating a chatbot into your React application can enhance user experience and provide valuable assistance to your users. With the availability of various libraries and tools, setting up a modern chatbot in a React project has become more straightforward. In this article, we'll explore how to set
2 min read
How to build a chatbot using ChatGPT? A chatbot is a computer program designed to simulate human conversation, usually through text or voice interactions. They use natural language processing (NLP) and machine learning algorithms to understand and respond to user queries, providing a personalized experience. Chatbots can be used for a w
6 min read
How to Build a JavaScript App with ChatGPT? AI is one of the most overhyped techs right now in the market. It is said that it will soon replace Software Engineers in creating complex software applications. In this article, we will test ChatGPT to create a JavaScript application by giving ChatGPT the prompts and will see if it can actually mak
6 min read
Use of CORS in Node.js The word CORS stands for "Cross-Origin Resource Sharing". Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other th
4 min read
How to Create Your Own ChatGPT Plugin Plugin is a software extension that brings in additional functionalities to an already existing application, especially in cases where implementing additional functionalities in the base code will be very complex and time-consuming.Plugins are one of the best ways to use services beyond limitations.
11 min read
How to Connect Node.js to Woocommerce API ? WooCommerce is one of the most popular e-commerce platforms available, powering over 30% of all online stores. It is built on top of WordPress and provides a powerful API for developers to interact with their store data programmatically. If you are building a Node.js application that interacts with
4 min read