top of page

How to integrate ChatGPT-3.5 with Node.js

ChatGPT has gone viral recently, and it seems like countless companies have integrated the OpenAI chat into their websites. As a developer, it could be a very useful skill to understand how exactly this gets done. This tutorial walks through how to achieve ChatGPT integration with a Node.js backend.


Set up a Node.js Project


If you don't already have a Node.js project, create a new directory for your project and initialize it with npm:


mkdir chatgpt-integration
cd chatgpt-integration
npm init -y

Install Dependencies


You will need some npm packages to make HTTP requests and handle the API communication. Install express, axios, and any other necessary dependencies:


npm install express axios

Create an OpenAI Account


If you haven't already, sign up for an account with OpenAI and create an API key. You'll need this key to authenticate your requests.


Set Up Environment Variables


Create a .env file in your project root to store your OpenAI API key and any other sensitive information. It should look something like this:


OPENAI_API_KEY=your-api-key-here

Ensure you never commit this file to a public repository, as it contains sensitive information.


Create an Express Server


Create a basic Express server in your project. Create a file named server.js and add the following code:


   const express = require('express');
   const app = express();
   const axios = require('axios');
   require('dotenv').config(); // Load environment variables

   const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

   app.use(express.json());

   // Define a route for sending a message to ChatGPT
   app.post('/chat', async (req, res) => {
     const message = req.body.message;

     try {
       const response = await axios.post(
         'https://api.openai.com/v1/engines/davinci-codex/completions',
         {
           prompt: message,
           max_tokens: 50, // Adjust this as needed
         },
         {
           headers: {
             'Content-Type': 'application/json',
             'Authorization': `Bearer ${OPENAI_API_KEY}`,
           },
         }
       );

       res.json({ reply: response.data.choices[0].text });
     } catch (error) {
       console.error(error);
       res.status(500).json({ error: 'An error occurred' });
     }
   });

   const PORT = process.env.PORT || 3000;
   app.listen(PORT, () => {
     console.log(`Server is running on port ${PORT}`);
   });

Make API Requests


You can now send a POST request to your /chat endpoint with a message as the request body to get a response from ChatGPT. You can use a tool like axios or fetch in your frontend to make these requests.


Run Your Server


Start your Node.js server:


node server.js

Your server should now be running and listening for incoming requests.


Test Your ChatGPT Integration


Use a tool like curl or Postman, or write a simple frontend application to make POST requests to your /chat endpoint with messages.


That's it! You've now integrated ChatGPT into your Node.js backend. Remember to handle any error cases, customize the API call parameters as needed, and secure your API key. Additionally, consider adding input validation and error handling for better robustness in a production environment.

bottom of page