Build a NodeJS Backend and Integrated with OpenAI Api

In this tutorial, we’ll build a Node.js API and integrate it with OpenAI’s API to enable AI interactions. You’ll also learn best practices and how to customize the responses.

Step 1: Create a New Folder for the Project

To begin, we need to organize our project. Open your terminal and run the following commands to create a folder named my-server and move inside it:

mkdir my-server cd my-server

This will help keep all the project files in one place.

Step 2: Initialize a Node.js Project

Now, initialize the Node.js project with the following command:

npm init -y

This will generate a package.json file with the default configuration. This file is essential for keeping track of dependencies and scripts for your project.

Step 3: Install the Necessary Dependencies

Next, we install some essential dependencies for our server:

npm install express dotenv cors

Dependency Descriptions:

  • express: A web framework for Node.js that simplifies server creation.
  • dotenv: For managing environment variables.
  • cors: To enable CORS (Cross-Origin Resource Sharing) and allow requests from other domains.

Step 4: Configure Environment Variables

It’s a good practice to keep sensitive configurations out of the source code. Create a .env file in the root directory of the project:

touch .env

Inside the .env file, define the port for your server:

PORT=8080

Remember not to share this file if it contains sensitive information, such as API keys.

Step 5: Update package.json to Use ES6 Modules

To use modern JavaScript syntax (import/export), add the following line to your package.json:

{ "type": "module", "scripts": { "start": "node index.js" } }

This will allow the use of ES6 syntax in your project.

Step 6: Create the Main Server File

Now, create the main file for the server. This file will contain the server’s code:

touch index.js

Step 7: Write the Server Code

Import Dependencies

In index.js, start by importing the necessary dependencies:

import express from 'express'; import { config } from 'dotenv'; import cors from 'cors';
  • express: To create the server.
  • dotenv: To load environment variables.
  • cors: To enable CORS in the application.

Initialize dotenv

Next, initialize dotenv to access the environment variables:

config();

Configure the Express Application and Port

Now, configure Express and set the port where the server will run:

const app = express(); const port = process.env.PORT || 8080;

Configure Middleware

Add middleware to enable CORS and handle JSON requests:

app.use(cors()); app.use(express.json());

Define a Test Route

Define a GET route that responds with a simple message to verify that the server is working properly:

app.get('/api/chat', async (req, res) => { res.json('The server is running'); });

Start the Server

Finally, make the application listen on the configured port:

app.listen(port, () => { console.log(`The server is running on port ${port}`); });

Step 8: Run the Server

To start the server, go back to the terminal and run the following command:

npm start

You should see the message: The server is running on port 8080 in the console.

Step 9: Test the Test Route

Open your browser and navigate to the following address to test that the server is working:

http://localhost:8080/api/chat

You should see the message: "The server is running".

Step 11: Install the OpenAI Package

To add artificial intelligence functionality, install OpenAI’s official package:

npm install openai

Step 12: Import and Configure OpenAI

Import OpenAI into your project and configure it with the API key found in your .env file:

import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, });

Make sure to add your OpenAI API key in the .env file:

OPENAI_API_KEY=your_api_key_here

Step 13: Update the Route to Use OpenAI

Modify the /api/chat route to send requests to OpenAI and return responses generated by the model:

app.post('/api/chat', async (req, res) => { try { const { messages } = req.body; const completion = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [{ role: 'system', content: 'You are a helpful assistant.' }, ...messages], }); res.json(completion.choices[0].message); } catch (error) { res.status(500).send('Error generating the response.'); } });

Conclusion

By following these steps, you will have created a basic server with Node.js and Express, and integrated it with the OpenAI API to generate automatic responses. Congratulations!

Subscribe to our Newsletter

To receive news, updates, code challenges, tech trends

© 2024 Codding Nutella. All rights reserved.