Building the largest Notifications Library in the world using ChatGPT, React, and NodeJS 🤯
Tags: javascript, programming, webdev, react
Published: 2023-02-13 14:11:05

# **TLDR;**

I am going to show you how to create a notification library like on this website:
https://notifications.directory

I will show you how to create thousands of notifications with ChatGPT and render it with React.

Happy if you can help me out by pressing the "love" sign, it helps me to create more articles!

![Love](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zclyb6tn464q33hc3t4h.png)

## Things you need to know

At the moment, he ChatGPT API isn't available.
The latest model from OpenAI is **"text-davinci-003"**.
If you're okay with using an older model, go ahead and give it a try!

But keep in mind that it's not as advanced as the current ChatGPT model **"text-davinci-002-render"**. In this tutorial, I'm going to show you a solution that was created by someone in the open-source community.

It's a good option for now, but please keep in mind that it might not always be available. OpenAI hasn't released its ChatGPT API yet, so this is just a temporary solution, this solution can't be used for commercial purposes.

![Meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0jlpsavxsw4hidl46m5.jpeg)

## What data do we need?

I will teach you how to do the same things we do in [The notification generator project](https://notifications.directory), simplified.

We will create three hierarchies.

- Categories Website types like
 - SaaS
 - E-commerce
 - Online marketplace
 - Travel
 - Etc..
- Notifications Types
 - SaaS: "Payment is due"
 - E-commerce: "Product out of stock", etc...
- Notifications
 - “Hi **NAME**, your payment is due for **DATE**”
 - “Hi **NAME**, product **PRODUCT_NAME** is out of stock.”

To create each hierarchy, we must have the data of the previous hierarchy.

While in Novu, we store everything inside MongoDB here we will do everything with a simple array.

## Novu - the first open-source notification infrastructure
Just a quick background about us. Novu is the first open-source [notification infrastructure](https://novu.co). We basically help to manage all the product notifications. It can be **In-App** (the bell icon like you have in Facebook), Emails, SMSs and so on.

![Novu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yn90yvsd87tgik03c08v.gif)

I would be super happy if you could give us a star! And let me also know in the comments ❤️
https://github.com/novuhq/novu

## Register to ChatGPT

Go over to [https://platform.openai.com/signup](https://auth0.openai.com/u/signup/identifier?state=hKFo2SAzcElQRTdMeDRGUXR5bkk1a2Q0a1BhbVowSTZLbHktM6Fur3VuaXZlcnNhbC1sb2dpbqN0aWTZIG40RjRWYXR1cUtOa0tPcDhlcnlDN0RPMVF1VTJXWERNo2NpZNkgVGRKSWNiZTE2V29USHROOTVueXl3aDVFNHlPbzZJdEc)

Register to OpenAI, head over to this endpoint: [https://chat.openai.com/api/auth/session](https://chat.openai.com/api/auth/session),

and grab the accessToken from the JSON.


![Access Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyxwii78f3v9ebteul0q.png)


## Setting up the project

We will start by creating the project and create our main file.

```bash
mkdir backend
cd backend
npm init
touch index.js
```

Let’s install our chatgpt library.

```bash
npm install @waylaidwanderer/chatgpt-api --save
```

This library uses Esm and not CommonJS. Therefore, it might be problematic for you if you try to implement it with NestJS - if you need help, let me know in the comments.

I will not separate the code into multiple files, as I want to keep it simple for the sake of this tutorial. Open index.js, and let's start writing.

Let's initiate our ChatGPT. As you can see, the library is using **"**chatgpt.hato.ai**",** a solution one of the community members found to use ChatGPT and was kind enough to deploy it on his server. While using this, your ChatGPT account will be exposed to an external resource, so please make sure you don't add any credit card information and that you are using the free ChatGPT version.
**Please be advised that the API is limited to 10 requests per second.**

```jsx
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'

const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
  reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
	modelOptions: {
	  model: 'text-davinci-002-render',
  },
});
```

Let’s create our database 🤣

```jsx
const categories = []
```

Final result of “categories” will look like this

```json
[
  {
    "category": "SaaS",
    "notificationTypes": [
      {
        "name": "Payment is due",
        "notifications": [
          "Hi {{name}}, your payment is due for. {{date}}"
        ]
      }
    ]
  }
]
```

Your code should look like this now:

```jsx
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'

const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
  reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
	modelOptions: {
	  model: 'text-davinci-002-render',
  },
});

const notifications = [];
```

Let’s write the code that will generate all the categories.

We want the prompt and the result to look like this:


![Chat1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3yp27amaifvuy81p2y4h.png)


The thing is that everything will come to us as a plain text.
We need a function that will create an array from the list.
I have created a quick one.
If you have something more efficient, let me know in the comments:

```jsx
const extractNumberedList = (text) => {
    return text.split("\n").reduce((all, current) => {
        const values = current.match(/\d+\.(.*)/);
        if (values?.length > 1) {
            return [...all, values[1].trim()];
        }

        return all;
    }, []);
}
```

Now the fun part.
We need all the possible categories, then run it through our function and map it to our database:

```jsx
const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));
```

Now we will iterate over the categories and start adding content to them. I am not going to use functional programming here for the first part.
I will use the “for loop” as it’s easier with async / await:

```jsx
for (const category of categories) {

}
```

Let’s start to create our notification types:

![notification type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqqs8m7ji59t52seosok.png)

```jsx
for (const category of categories) {
	const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
  const notificationTypes = extractNumberedList(res.response).map(p => ({name: p, notifications: []}));
}
```

And now, let’s add our notifications:

![notifications](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xc8oi7wt6e8zqca0ws9j.png)

```jsx
for (const category of categories) {
  // get all the notifications type
	const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
  // parse all the notification type and map them
  const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
  // get all the notifications for the notification type
  const notifications = await Promise.all(notificationTypes.map(async p => {
		const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
		return {
			...p,
			notifications: extractNumberedList(notificationRes.response)
		}
	}));
  // push it to the main array
	notificationTypes.notifications.push(...notifications);
}
```

The final code will be looking like this:

```jsx
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'

const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
  reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
	modelOptions: {
	  model: 'text-davinci-002-render',
  },
});

const categories = [];

const extractNumberedList = (text) => {
    return text.split("\n").reduce((all, current) => {
        const values = current.match(/\d+\.(.*)/);
        if (values?.length > 1) {
            return [...all, values[1].trim()];
        }

        return all;
    }, []);
}

const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));

for (const category of categories) {
  // get all the notifications type
	const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
  // parse all the notification type and map them
  const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
  // get all the notifications for the notification type
  const notifications = await Promise.all(notificationTypes.map(async p => {
		const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
		return {
			...p,
			notifications: extractNumberedList(notificationRes.response)
		}
	}));
  // push it to the main array
	notificationTypes.notifications.push(...notifications);
}
```

It can run in the background forever 🥳

We can quickly move it to a separate task / cron / queue, but we will not do it here.

While this thing is running in the background, let’s add here the API that our frontend can use

Let’s go back to our command line and write:

```bash
npm install express --save
```

We will do the simplest thing and just serve our categories variable.

Feel free to take it to the next level with an actual database:

```jsx

import express from 'express';
const app = express()
const port = 3000

app.get('/', (req, res) => {
  return categories;
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
```

And the complete code is as follows:

```jsx

import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api';
import express from 'express';

const categories = [];
const app = express();
const port = 3000;

const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
  reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
	modelOptions: {
	  model: 'text-davinci-002-render',
  },
});

const extractNumberedList = (text) => {
    return text.split("\n").reduce((all, current) => {
        const values = current.match(/\d+\.(.*)/);
        if (values?.length > 1) {
            return [...all, values[1].trim()];
        }

        return all;
    }, []);
}

app.get('/', (req, res) => {
  return categories;
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
});

const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));

for (const category of categories) {
  // get all the notifications type
	const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
  // parse all the notification type and map them
  const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
  // get all the notifications for the notification type
  const notifications = await Promise.all(notificationTypes.map(async p => {
		const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
		return {
			...p,
			notifications: extractNumberedList(notificationRes.response)
		}
	}));
  // push it to the main array
	notificationTypes.notifications.push(...notifications);
}
```

NODE.JS ✅

Now let’s move over to react to display all of our categories.

I will do the simplest thing of aggregating everything inside of a `<ul>`

Let’s right some bash commands:

```bash
cd ..
npx create-react-app frontend
cd frontend
```

I will be using axios to get all the results from the database, feel free to use fetch / react-query etc…

```bash
npm install axios
```

Let’s open our main component at “src/App.js” and add some imports

```jsx
import {useState, useCallback, useEffect} from 'react';
import axios from 'axios';
```

Let’s open our main component at “src/App.js” and add a new state that will contain all of our database from the server:

```jsx
const [categories, setCategories] = useState([]);
```

And now, we will write the function that will get all the information from the server

```jsx
const serverInformation = useCallback(async () => {
	const {data} = await axios.get('http://localhost:3000');
	setCategories(data);
}, []);
```

Add it to our useEffect, that will run as soon as the component is loaded

```jsx
useEffect(() => {
	serverInformation();
}, []);
```

And now, we will render everything on the screen

```jsx
<ul>
	{categories.map(cat => (
		<li>
			{cat.category}
			<ul>
				{cat.notificationTypes.map(notificationType => (
					<li>
						{notificationType.name}
						<ul>
							{notificationType.notifications.map(notification => (
								<li>
									{notification}
								<li>
							)}
						</ul>
					<li>
				)}
			</ul>
		<li>
	)}
</ul>
```

And that’s it! We have rendered the entire list!!!

The full code of App.js would look like this:

```jsx
import {useState, useCallback, useEffect} from 'react';
import axios from 'axios';

function App() {
	const [categories, setCategories] = useState([]);

	useEffect(() => {
		serverInformation();
	}, []);

	const serverInformation = useCallback(async () => {
		const {data} = await axios.get('http://localhost:3000');
		setCategories(data);
	}, []);

	return (
		<ul>
			{categories.map(cat => (
				<li>
					{cat.category}
					<ul>
						{cat.notificationTypes.map(notificationType => (
							<li>
								{notificationType.name}
								<ul>
									{notificationType.notifications.map(notification => (
										<li>
											{notification}
										<li>
									)}
								</ul>
							<li>
						)}
					</ul>
				<li>
			)}
		</ul>
	);
}
```

Of course, this is the short version of the frontend.

You can find the complete frontend code (with the amazing design) here:
https://github.com/novuhq/notification-directory-react

![screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tf0r0o3h6rvyorzj9lwt.png)

I hope you have learned something. Until next time 😎

## Help me out!
If you feel like this article helped you, I would be super happy if you could give us a star! And let me also know in the comments ❤️

https://github.com/novuhq/novu
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5d6ugy7vbn2fl5kggbh.gif)