Unlock the Future: Your Web App With ChatGPT, React JS, and Node.js ⚛️ 🔥 🚀
Tags: webdev, tutorial, ai, chatgpt
Published: 2024-03-05 13:48:11

This comprehensive guide will walk you through the process of incorporating **OpenAI's ChatGPT model** and the [**nlux**](https://github.com/nluxai/nlux) **AI chatbot library** into a web application using Node.js for the backend and React JS for the frontend. 

Our aim is to make this guide as user-friendly as possible for you, breaking down each step in simple terms and explaining why each library is important.

## Understanding the Libraries

- **[Express.js](https://expressjs.com/):** A fast, unopinionated, minimalist web framework for Node.js, ideal for building web applications and APIs. It simplifies routing, middleware, handling requests, and more.

- **[@nlux/react](https://github.com/nluxai/nlux):** A feature-rich library designed to simplify the integration of AI chatbos within React applications, providing components and hooks for building LLM-powered interfaces.

- **[@nlbridge/express](https://www.npmjs.com/package/@nlbridge/express):** A lightweight Node.js library that provides utilities, middleware, and a development server for building APIs powered by large language models.

- **[React JS](https://react.dev/):** A JavaScript library for building user interfaces, particularly known for its efficient update and render of the right components when data changes.

## Step-by-Step Integration

### 1. **Obtaining OpenAI API Key**

- Sign up at [OpenAI](https://auth0.openai.com/u/signup/identifier?state=hKFo2SBFa1JIdG13Q2piOHY0dmhBU2pQZU4yamhQcjdNMTFfSKFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIE5hbEVjQ2hwUFptdk11dnIzUzF1WURqR0xxeWFzYjdqo2NpZNkgRFJpdnNubTJNdTQyVDNLT3BxZHR3QjNOWXZpSFl6d0Q) and navigate to the [API keys](https://platform.openai.com/api-keys) section to generate a new key. This key is crucial for authenticating your requests to the ChatGPT model.

- Click the `Create new secret` key button

![Screenshot of how to create open api secret key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0s54b3f6h8kbjft9ixa.png)

- Give your API key a name and click `Create secret key`

- Copy the API key and save it in a safe place. You will need it to configure the OpenAI _nlux_ adapter.

## Creating a Node.js Middleware To Connect to ChatGPT

In the next 2 steps, we will create a simple endpoint that connects to ChatGPT. We will use `@nlbridge/express` for that prupose.

### 2. **Setting Up an Express.js Server**

- **Installation:** Ensure [Node.js](https://nodejs.org/en) (preferably the latest LTS version) is installed, then initialize a new Node.js project. Install Express.js and its types for TypeScript support.

- **Server Creation:** Write a simple server in TypeScript that listens for requests. This server acts as the backbone of your application, facilitating communication with the OpenAI API.

**Example Code:**

```ts
import express from 'express';
import cors from 'cors';

const app = express();
const port = 8080;

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

app.get('/', (req, res) => {
  res.send('Welcome to our NLUX + Node.js demo server!');
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});
```
**Run the Express.js server**
Run your Express.js application using the following command:

```bash
npx ts-node index.ts
```

Then navigate to this URL: `http://localhost:8080` in your browser, you should see the following in your browser: 

![Screenshot of the express server api built to test the server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vdzl5l55e7tkruelpj9.png)

### 3. **Integrating `nlbridge` Middleware**
Incorporate [@nlbridge/express](https://www.npmjs.com/package/@nlbridge/express) to bridge the OpenAI API with the [NLUX](https://github.com/nluxai/nlux) library, facilitating the creation of a server endpoint for AI interactions.

**Example Code:**

```ts
import { defaultMiddleware } from '@nlbridge/express';

app.post('/chat-api', defaultMiddleware('openai', {
  apiKey: 'YOUR_OPENAI_API_KEY',
  chatModel: 'gpt-3.5-turbo',
}));
```

**Explanations to the code sample above:**

This snippet of code demonstrates how to set up a server endpoint in a Node.js application using Express and the `@nlbridge/express` library, specifically for creating an AI chat functionality powered by OpenAI's ChatGPT model.

[Read more about `nlbridge`](https://www.npmjs.com/package/@nlbridge/express)

1. **Importing `defaultMiddleware`**:
   - The line `import { defaultMiddleware } from '@nlbridge/express';` imports the `defaultMiddleware` function from the `@nlbridge/express` package. This function is designed to simplify the integration of language models, like ChatGPT, with your web application.

2. **Creating a Server Endpoint**:
   - `app.post('/chat-api', defaultMiddleware('openai', {...}));` sets up a new POST endpoint at `/chat-api` on your server. This endpoint uses the `defaultMiddleware` function to process requests and responses between your application and the OpenAI API.

3. **Configuring the Middleware**:
   - Inside the `defaultMiddleware` function, we specify 'openai' as the middleware type, indicating that we're setting up an endpoint to interact with the OpenAI API.
   - The configuration object provided as the second argument contains two crucial pieces of information:
     - `apiKey: 'YOUR_OPENAI_API_KEY'`: This is where you place your unique API key from OpenAI. The key authenticates requests from your application to the OpenAI service, ensuring secure access to the ChatGPT model.
     - `chatModel: 'gpt-3.5-turbo'`: This specifies the version of the ChatGPT model you wish to use. In this case, 'gpt-3.5-turbo' refers to a highly efficient and cost-effective variant of the GPT-3.5 model, optimized for quick responses suitable for chat applications.

In essence, this code integrates an AI chat capability into your application, allowing users to interact with the ChatGPT model via a dedicated server endpoint. By incorporating this functionality, developers can enhance their applications with intelligent conversational experiences, leveraging the advanced natural language processing capabilities of ChatGPT.

**Note:** Make sure to replace `<YOUR_OPENAI_API_KEY>` with your actual OpenAI API key obtained in _Step 1_. Then restart your server, and you will have a new endpoint at `POST http://localhost:3000/chat-api` that is powered by OpenAI's gpt-3.5-turbo model, and ready for nlux integration.

It's important to note that the new API is created with post method.
This is a requirement for nlbridge integration.

Now, let's build the frontend using ReactJS

## Creating an AI chatbot Interface

### 4. **Installing NLUX Packages**

With the backend in place, move on to the frontend by setting up a ReactJS project and installing NLUX packages for creating AI chat components.

### Quick Setup with Vite: The commands:

```bash
npm create vite@latest my-ai-chat-app -- --template react-ts
cd my-ai-chat-app
npm install
npm run dev
```

Quickly scaffold a new React project using Vite, selecting a template that supports both React and TypeScript. This setup allows for rapid development and testing.

Once you have your React JS app set up, let's go and install the **`nlux` dependencies**:

```
npm install @nlux/react @nlux/nlbridge-react
```

### 5. **Crafting the AI Chat Component**
Utilize the `useChatAdapter` hook and `AiChat` component from NLUX to develop your chat interface, ensuring seamless communication with the backend server.

**Example Code:**

```ts
import { AiChat } from '@nlux/react';
import { useChatAdapter } from '@nlux/nlbridge-react';

const adapterOptions = {
  url: 'http://localhost:8080/chat-api',
};

const App = () => {
  const nlbridgeAdapter = useChatAdapter(adapterOptions);

  return (
    <AiChat
      adapter={nlbridgeAdapter}
      promptBoxOptions={{ placeholder: 'How can I help you today?' }}
    />
  );
};

export default App;
```

### 6. **Styling of the Chat UI**

Install and import NLUX's default CSS theme to ensure your chat interface is visually appealing.

```bash
npm install @nlux/themes
```

Then in your main chat component, import it as following:

```
import '@nlux/themes/nova.css';
```

**Output:**

![Screenshot of the code output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltiqfjgib0cykz5wp52a.gif)


### 🌟 Support NLUX on GitHub 🌟

NLUX is an open-source project, dedicated to bridging the gap between web development and conversational AI technologies. If you've found value in this guide or in the NLUX library itself, consider giving us a ⭐ on [GitHub](https://github.com/nluxai/nlux). 
Your support helps us continue to innovate and provide valuable resources to the developer community. Let's build the future of conversational interfaces together!

## Conclusion

This comprehensive guide outlines the steps necessary to integrate cutting-edge AI chatbots into your web applications, from backend setup with Node.js and Express.js to frontend creation with ReactJS and [NLUX](https://nlux.dev/learn/get-started/nlux-nodejs-nlbridge-chatgpt). By following these steps, developers can unlock new potentials in user interaction, offering more engaging and intelligent conversational experiences.


Thanks for reading...
**Happy Coding!**