Node Backend Setup
The backend is a Node.js API server built with Express. It connects to OpenAI’s API and handles user requests through api route. Key features include:
Simple routing with Express.
Environment configuration using .env and dotenv.
Middleware for JSON and CORS support.
Integration with the official OpenAI SDK using a helper function (chatHelper) that formats and sends messages to the language model.
This part sets up a clear backend logic flow to receive chat input, process it through OpenAI, and return the response to the frontend.
a. Navigate to the Backend Project Folder
Sección titulada «a. Navigate to the Backend Project Folder»This guide walks you through creating a basic backend using Node.js and Express.
Create a folder for your backend project and navigate into it:
mkdir nodecd node- Initialize the Project and Create the
.envFile
If you haven’t already, initialize a Node.js project and create the .env file:
npm init -ytouch .env- Install Required Dependencies
Run the following command to install the required libraries:
npm install -s express cors dotenv openai multernpm install -D nodemonexpress: Web framework for Node.js.cors: Middleware to enable CORS.dotenv: Loads environment variables from the.envfile.openai: Official library to interact with the OpenAI API.multer: Middleware for handling file uploads in Node.js.nodemon: Development tool that automatically restarts the server when file changes are detected.
c. Configure package.json
Sección titulada «c. Configure package.json»Open the package.json file and update it to include the start script and define the project as an ES module:
{ "type": "module", "scripts": { "start": "node index.js", "dev":"nodemon index.js" }}type: "module": Enables modern ES module syntax (importinstead ofrequire).startscript: Allows running the server withnpm start.
d. Add Environment Variables
Sección titulada «d. Add Environment Variables»Open the .env file and add your OpenAI API key and server port:
OPENAI_API_KEY=your_api_key_herePORT=8000- OPENAI_API_KEY: Key provided by OpenAI to authenticate requests.
- PORT: Port on which the server will run (default is
8000).
f. Create the index.js File
Sección titulada «f. Create the index.js File»Inside the root of your backend folder, create a file named index.js with the following content:
// Import the Express frameworkimport express from "express";
// Import the 'config' function from the 'dotenv' package to manage environment variablesimport { config } from "dotenv";
// Import the CORS middleware to handle Cross-Origin Resource Sharingimport cors from "cors";
// Load environment variables from a .env file into process.envconfig();
// Create an instance of an Express applicationconst app = express();
// Define the port number from environment variables or default to 8000const port = process.env.PORT || 8000;
// Use the CORS middleware to allow cross-origin requestsapp.use(cors());
// Use built-in middleware to parse incoming JSON requestsapp.use(express.json());
// Define a GET route at the root URL ('/') that sends a success messageapp.get("/", (req, res) => { res.send("Backend is running successfully.");});
// Start the server and listen on the specified port, logging a message when it's runningapp.listen(port, () => {
});Run the Backend Server
Sección titulada «Run the Backend Server»You can now start the backend with the following command:
npm run devVisit http://localhost:8000/ in your browser or use a tool like Postman to confirm it returns:
Backend is running successfully.