category: How toFeb 06, 2023

Master Notifications With ChatGPT, React and NodeJS 🧨

In this tutorial, you'll learn how to build a web application that allows you to send notifications generated by ChatGPT to your users, using React and NodeJS.

Intro

I have built many products in my life.
In all of them I had to send notifications to the user in some form.

It could be a “Welcome Email” or informing the users they haven’t paid their last invoice 😅

But one thing was sure. I am a programmer, not a copywriter.
So how do I come up with the right message for my notifications?

I was playing with GPT+3, more than a year ago, the results were nice, but not something I could use in production with automation.

But ChatGPT changed the game.

What is ChatGPT?

ChatGPT is an AI language model trained by OpenAI to generate text and interact with users in a human-like conversational manner. It is worth mentioning that ChatGPT is free and open to public use.

Users can submit requests and get information or answers to questions from a wide range of topics such as history, science, mathematics, and current events in just a few seconds.

ChatGPT performs other tasks, such as proofreading, paraphrasing, and translation. It can also help with writing, debugging, and explaining code snippets. Its wide range of capabilities is the reason why ChatGPT has been trending.

The main problem is that it’s not yet available to use with an API.

But that won’t stop us 😈

Novu – the first open-source notification infrastructure

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

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

Limitation with ChatGPT

As I mentioned before, ChatGPT is not available as a public API.
So, to use it, we have to scrape our way in.
It means we will perform a full browser automation where we log in to the OpenAI website, solve their captcha (for that, you can use 2captcha), and send an API request with the OpenAI cookies.

Fortunately, somebody already built a public library that can do all of that here.

FYI this is not an API, and you will hit a hard limitation if you try to make many requests, and of course, you won’t be able to use it for live requests.

If you want to use it, use a queue and do background processing. If you want to know how to do it, write me in the comments, and I will write another article about it.

Project Set up

Here, I’ll guide you through creating the project environment for the web application. We’ll use React.js for the front end and Node.js for the backend server.

Create the project folder for the web application by running the code below:

1mkdir react-chatgpt
2cd react-chatgpt
3mkdir client server

Setting up the Node.js server

Navigate into the server folder and create a package.json file.

1cd server & npm init -y

Install Express, Nodemon, and the CORS library.

1npm install express cors nodemon

ExpressJS is a fast, minimalist framework that provides several features for building web applications in Node.js, CORS is a Node.js package that allows communication between different domains, and Nodemon is a Node.js tool that automatically restarts the server after detecting file changes.

Create an index.js file – the entry point to the web server.

1touch index.js

Set up a Node.js server using Express.js. The code snippet below returns a JSON object when you visit the http://localhost:4000/api in your browser.

1//👇🏻index.js
2const express = require("express");
3const cors = require("cors");
4const app = express();
5const PORT = 4000;
6
7app.use(express.urlencoded({ extended: true }));
8app.use(express.json());
9app.use(cors());
10
11app.get("/api", (req, res) => {
12    res.json({
13        message: "Hello world",
14    });
15});
16
17app.listen(PORT, () => {
18    console.log(`Server listening on ${PORT}`);
19});

Install the ChatGPT API library and Puppeteer. The ChatGPT API uses Puppeteer as an optional peer dependency to automate bypassing the Cloudflare protections.

1npm install chatgpt puppeteer

To use the ChatGPT API within the server/index.js, you need to configure the file to use both the require and import keywords for importing libraries.

Therefore, update the server/package.json to contain the type keyword.

1{ "type": "module" }

Add the code snippet below at the top of the server/index.js file.

1import { createRequire } from "module";
2const require = createRequire(import.meta.url);
3//...other code statements

Once you have completed the last two steps, you can now use ChatGPT within the index.js file.

Configure Nodemon by adding the start command to the list of scripts in the package.json file. The code snippet below starts the server using Nodemon.

1//In server/package.json
2
3"scripts": {
4    "test": "echo \"Error: no test specified\" && exit 1",
5    "start": "nodemon index.js"
6  },

Congratulations! You can now start the server by using the command below.

1npm start

Setting up the React application

Navigate into the client folder via your terminal and create a new React.js project.

1cd client
2npx create-react-app ./

Install React Router – a JavaScript library that enables us to navigate between pages in a React application.

1npm install react-router-dom

Delete the redundant files, such as the logo and the test files from the React app, and update the App.js file to display “Hello World” as below.

1function App() {
2    return (
3        <div>
4            <p>Hello World!</p>
5        </div>
6    );
7}
8export default App;

Navigate into the src/index.css file and copy the code below. It contains all the CSS required for styling this project.

1@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
2* {
3    box-sizing: border-box;
4    margin: 0;
5    padding: 0;
6    font-family: "Space Grotesk", sans-serif;
7}
8body {
9    margin: 0;
10    padding: 0;
11}
12textarea,
13select {
14    padding: 10px 15px;
15    margin-bottom: 15px;
16    border: 1px solid #ddd;
17    border-radius: 5px;
18}
19.notification__form {
20    width: 80%;
21    display: flex;
22    align-items: left;
23    justify-content: center;
24    flex-direction: column;
25}
26.homeContainer h3,
27textarea {
28    margin-bottom: 20px;
29}
30.notification__form button {
31    width: 200px;
32    padding: 15px 10px;
33    cursor: pointer;
34    outline: none;
35    border: none;
36    background-color: #82aae3;
37    border-radius: 5px;
38    margin-bottom: 15px;
39}
40.navbar {
41    width: 100%;
42    height: 10vh;
43    padding: 20px;
44    background-color: #82aae3;
45    display: flex;
46    align-items: center;
47    justify-content: space-between;
48}
49.homeContainer {
50    width: 100%;
51    min-height: 100vh;
52    display: flex;
53    align-items: center;
54    justify-content: center;
55    flex-direction: column;
56}

Update the App.js file to render a Home component as below:

1import React from "react";
2import { BrowserRouter, Route, Routes } from "react-router-dom";
3import Home from "./components/Home";
4
5const App = () => {
6    return (
7        <BrowserRouter>
8            <Routes>
9                <Route path='/' element={<Home />} />
10            </Routes>
11        </BrowserRouter>
12    );
13};
14
15export default App;

From the code snippet above, I imported the Home component. Create a components folder containing the Home.js file as done below:

1cd client
2mkdir components
3cd components
4touch Home.js

Copy the code snippet below into the Home.js file:

1import React, { useState } from "react";
2
3const Home = () => {
4    const [message, setMessage] = useState("");
5    const [subscriber, setSubscriber] = useState("");
6
7    const handleSubmit = (e) => {
8        e.preventDefault();
9        console.log({ message, subscriber });
10        setMessage("");
11        setSubscriber("");
12    };
13
14    return (
15        <div className='home'>
16            <nav className='navbar'>
17                <h2>Notify</h2>
18            </nav>
19            <main className='homeContainer'>
20                <h3>Send notifications to your users</h3>
21                <form
22                    className='notification__form'
23                    onSubmit={handleSubmit}
24                    method='POST'
25                >
26                    <label htmlFor='title'>Notification Title</label>
27                    <textarea
28                        rows={5}
29                        name='title'
30                        required
31                        value={message}
32                        onChange={(e) => setMessage(e.target.value)}
33                        placeholder='Let the user know that'
34                    />
35                    <label htmlFor='subscriber'>Subscribers</label>
36
37                    <select
38                        value={subscriber}
39                        name='subscriber'
40                        onChange={(e) => setSubscriber(e.target.value)}
41                    >
42                        <option value='Select'>Select</option>
43                    </select>
44                    <button>SEND NOTIFICATION</button>
45                </form>
46            </main>
47        </div>
48    );
49};
50
51export default Home;
Interface

How to add Novu to a React and Node.js application

We will be using Novu to send In-App notifications, but if you want to build your on in-app notifications, feel free to skip this step.

Adding Novu to a React application

Create a Novu project by running the code below within the client folder.

1cd client
2npx novu init

You will need to sign in with Github before creating a Novu project. The code snippet below contains the steps you should follow after running npx novu init.

1Now let's setup your account and send your first notification
2❓ What is your application name? Devto Clone
3❓ Now lets setup your environment. How would you like to proceed?
4   > Create a free cloud account (Recommended)
5❓ Create your account with:
6   > Sign-in with GitHub
7❓ I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy)
8    > Yes
9✔️ Create your account successfully.
10
11We've created a demo web page for you to see novu notifications in action.
12Visit: http://localhost:57807/demo to continue

Visit the demo web page http://localhost:52685/demo, copy your subscriber ID from the page, and click the Skip Tutorial button. We’ll be using it later in this tutorial.

Novu

Install Novu Notification package as a dependency in your React project.

1npm install @novu/notification-center

Update the components/Home.js file to contain Novu and its required elements from the documentation.

1import {
2    NovuProvider,
3    PopoverNotificationCenter,
4    NotificationBell,
5} from "@novu/notification-center";
6import { useNavigate } from "react-router-dom";
7
8const Home = () => {
9    const navigate = useNavigate();
10
11    const onNotificationClick = (notification) => {
12        navigate(notification.cta.data.url);
13    };
14    //...other statements
15
16    return (
17        <div className='home'>
18            <nav className='navbar'>
19                <h2>Notify</h2>
20                <NovuProvider
21                    subscriberId={"<YOUR_SUBSCRIBER_ID>"}
22                    applicationIdentifier={"<YOUR_APP_ID>"}
23                >
24                    <PopoverNotificationCenter onNotificationClick={onNotificationClick}>
25                        {({ unseenCount }) => (
26                            <NotificationBell unseenCount={unseenCount} colorScheme='light' />
27                        )}
28                    </PopoverNotificationCenter>
29                </NovuProvider>
30            </nav>
31            <main className='homeContainer'>...</main>
32        </div>
33    );
34};

The code snippet above adds Novu’s notification bell icon to the navigation bar, enabling us to view all the app notifications.

Notification

The NovuProvider component requires your Subscriber ID – copied earlier from http://localhost:52685/demo and your application ID available in the Settings section under API Keys on the Novu Manage Platform.

Next, let’s create the notification workflow and template for the application.

Open the Novu Manage Platform in your browser and create a notification template.

List

Select the template, click on Workflow Editor, and ensure the workflow is as below:

Template

Click on the In-App step and edit the template to contain a message variable, as done below. The message variable will contain the notifications generated by ChatGPT.

1{{message}}

Save the template by clicking Update button.

Adding Novu to a Node.js application

Navigate into the server folder and install the Novu SDK for Node.js.

1cd server
2npm install @novu/node

Import Novu from the package and create an instance using your API Key.

1//server/index.js
2
3const { Novu } = require("@novu/node");
4const novu = new Novu("<YOUR_API_KEY>");

Congratulations! You’ve successfully added Novu to your web application. In the upcoming section, you’ll learn how to send AI-generated notifications to your users via Novu.

How to send ChatGPT notifications to your users via Novu

In this section, I’ll guide you through generating notifications from ChatGPT for different use cases and sending them to your Novu subscribers.
The application will allow you to specify the type of notification you want and select a subscriber that will receive the message.
We’ve created a form field within the Home.js. Next, let’s fetch the list of subscribers and display them within the component.

Getting and displaying your Novu subscribers

Add a route within the index.js file that gets the list of subscribers from Novu.

1app.get("/subscribers", async (req, res) => {
2    try {
3        const { data } = await novu.subscribers.list(0);
4        const resultData = data.data;
5        //👇🏻 Returns subscibers with an id, and first and last names
6        const subscribers = resultData.filter(
7            (d) => d.firstName && d.lastName && d.subscriberId
8        );
9        res.json(subscribers);
10    } catch (err) {
11        console.error(err);
12    }
13});

Create a function that sends a request to the /subscribers endpoint and displays the subscribers on page load within the React application.

1//👇🏻 State representing the list of subscribers
2const [subscribers, setSubscribers] = useState([
3    { firstName: "", lastName: "", subscriberId: "Select", _id: "null" },
4]);
5
6//👇🏻 Fetch the list of subscribers on page load
7useEffect(() => {
8    async function fetchSubscribers() {
9        try {
10            const request = await fetch("http://localhost:4000/subscribers");
11            const response = await request.json();
12            setSubscribers([...subscribers, ...response]);
13        } catch (err) {
14            console.error(err);
15        }
16    }
17    fetchSubscribers();
18}, []);

Update the select tag within the Home component to render the list of subscribers as below:

1<select
2    value={subscriber}
3    name='subscriber'
4    onChange={(e) => setSubscriber(e.target.value)}
5>
6    {subscribers.map((s) => (
7        <option
8            key={s._id}
9            value={`${s.firstName} ${s.lastName} - ${s.subscriberId}`}
10        >{`${s.firstName} ${s.lastName} - ${s.subscriberId}`}</option>
11    ))}
12</select>

Generating the notifications from ChatGPT

Create a route within index.js that accepts the notification title and subscriber from the user.

1app.post("/notify", (req, res) => {
2    //👇🏻 Destructure the message and subscriber from the object
3    const { message, subscriber } = req.body;
4    //👇🏻 Separates the first name and the subscriber ID
5    const subscriberDetails = subscriber.split(" ");
6    const firstName = subscriberDetails[0];
7    const subscriberId = subscriberDetails[3];
8    //👇🏻 Added some specifications to the message to enable the AI generate a concise notification.
9    const fullMessage = `I have a notification system and I want to send the user a notification about "${message}" can you write me one?
10please use double curly brackets for variables.
11make it short, and use only one variable for the user name.
12Please just write 1 notification without any intro.`;
13
14    //👇🏻 Log the required variables to the console
15    console.log({ firstName, subscriberId, fullMessage });
16});

Next, let’s submit the form details to the /notify route on the server. Create a function that makes a POST request to the endpoint when the form is submitted.

1//👇🏻 Makes the POST request
2async function sendNotification() {
3    try {
4        const request = await fetch("http://localhost:4000/notify", {
5            method: "POST",
6            body: JSON.stringify({
7                message,
8                subscriber,
9            }),
10            headers: {
11                Accept: "application/json",
12                "Content-Type": "application/json",
13            },
14        });
15        const data = await request.json();
16        console.log(data);
17    } catch (err) {
18        console.error(err);
19    }
20}
21
22//👇🏻 Runs when a user submits the form
23const handleSubmit = (e) => {
24    e.preventDefault();
25    //👇🏻 Calls the function
26    sendNotification();
27    setMessage("");
28    setSubscriber("");
29};

Update the /notify route to pass the necessary variables into another function.

1app.post("/notify", (req, res) => {
2    const { message, subscriber } = req.body;
3    const subscriberDetails = subscriber.split(" ");
4    const firstName = subscriberDetails[0];
5    const subscriberId = subscriberDetails[3];
6    const fullMessage = `I have a notification system and I want to send the user a notification about "${message}" can you write me one?
7please use double curly brackets for variables.
8make it short, and use only one variable for the user name.
9Please just write 1 notification without any intro.`;
10    console.log({ firstName, subscriberId, fullMessage });
11
12    //👇🏻 Pass the variables as a parameter into the function
13    chatgptFunction(fullMessage, subscriberId, firstName, res);
14});

Create the chatgptFunction as done below:

1//👇🏻 Holds the AI-generated notification
2let chatgptResult = "";
3
4async function chatgptFunction(message, subscriberId, firstName, res) {
5    // use puppeteer to bypass cloudflare (headful because of captchas)
6    const api = new ChatGPTAPIBrowser({
7        email: "<YOUR_CHATGPT_EMAIL>",
8        password: "<YOUR_CHATGPT_PASSWORD>",
9    });
10    //👇🏻 Open up the login screen on the browser
11    await api.initSession();
12    const result = await api.sendMessage(message);
13    chatgptResult = result.response;
14    //👇🏻 Replace the user variable with the user's first name
15    const notificationString = chatgptResult.replace("{{user}}", firstName);
16
17    console.log(notificationString, subscriberId);
18}

Finally, let’s send the notification to the subscriber via the ID. Create another function that accepts the notificationString and subscriberId and sends the notification.

1async function chatgptFunction(message, subscriberId, firstName, res) {
2    // use puppeteer to bypass cloudflare (headful because of captchas)
3    const api = new ChatGPTAPIBrowser({
4        email: "<YOUR_CHATGPT_EMAIL>",
5        password: "<YOUR_CHATGPT_PASSWORD>",
6    });
7    await api.initSession();
8    const result = await api.sendMessage(message);
9    chatgptResult = result.response;
10    const notificationString = chatgptResult.replace("{{user}}", firstName);
11
12    //👇🏻 Pass the necessary variables as parameters
13    sendNotification(notificationString, subscriberId, res);
14}
15
16//👇🏻 Sends the notification via Novu
17async function sendNotification(data, subscriberId, res) {
18    try {
19        let result = await novu.trigger("<NOTIFICATION_TEMPLATE_ID>", {
20            to: {
21                subscriberId: subscriberId,
22            },
23            payload: {
24                message: data,
25            },
26        });
27        return res.json({ message: result });
28    } catch (err) {
29        return res.json({ error_message: err });
30    }
31}

Congratulations!🎉 You’ve completed the project for this tutorial.

Congrats

Conclusion

So far, we have covered

  • what ChatGPT is,
  • how to communicate with it in a Node.js application, and
  • how to send ChatGPT-generated notifications to users via Novu in a React and Node.js application.

This tutorial walks you through an example of an application you can build using Novu and ChatGPT. ChatGPT can be seen as the ultimate personal assistant, very useful in various fields to enable us to work smarter and better.

The source code for this tutorial is available here: https://github.com/novuhq/blog/tree/main/sending-chatgpt-notifications-with-novu

Thank you for reading!

Help me out!

If you feel like this article helped you understand WebSockets better! 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

Related Posts

category: How to

A Proper Guide to Web and Mobile Push Notification Service

Implement push notification services successfully by following this actionable guide on choosing platforms, setting up, and personalizing notifications for better results.

Emil Pearce
Emil Pearce
category: How to

How to Add Real-Time Notifications to a React App

Learn how to integrate real-time notifications into your React app using WebSockets, Server-Sent Events, Firebase Cloud Messaging (FCM), and Novu for improved user engagement and instant updates.

Emil Pearce
Emil Pearce
category: How to

A Developer’s Guide to Choosing the Best Notification Platform

A comprehensive guide for developers on selecting notification platforms, covering different types of notifications (push, in-app, email, SMS, and chat), key features to consider, popular providers, and best practices for implementation. Learn how to evaluate notification platforms based on integration ease, cost-effectiveness, scalability, and security, with practical insights on platforms like FCM, Twilio, SendGrid, and Novu.

Emil Pearce
Emil Pearce