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.

Author:Nevo David
Nevo David

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:

mkdir react-chatgpt
cd react-chatgpt
mkdir client server

Setting up the Node.js server

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

cd server & npm init -y

Install Express, Nodemon, and the CORS library.

npm 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.

touch 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.

//\ud83d\udc47\ud83c\udffbindex.js
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

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

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

npm 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.

{ "type": "module" }

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

import { createRequire } from "module";
const require = createRequire(import.meta.url);
//...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.

//In server/package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },

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

npm start

Setting up the React application

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

cd client
npx create-react-app ./

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

npm 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.

function App() {
    return (
        
            Hello World!</p>
        </div>
    );
}
export default App;

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

@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family: "Space Grotesk", sans-serif;
}
body {
    margin: 0;
    padding: 0;
}
textarea,
select {
    padding: 10px 15px;
    margin-bottom: 15px;
    border: 1px solid #ddd;
    border-radius: 5px;
}
.notification__form {
    width: 80%;
    display: flex;
    align-items: left;
    justify-content: center;
    flex-direction: column;
}
.homeContainer h3,
textarea {
    margin-bottom: 20px;
}
.notification__form button {
    width: 200px;
    padding: 15px 10px;
    cursor: pointer;
    outline: none;
    border: none;
    background-color: #82aae3;
    border-radius: 5px;
    margin-bottom: 15px;
}
.navbar {
    width: 100%;
    height: 10vh;
    padding: 20px;
    background-color: #82aae3;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.homeContainer {
    width: 100%;
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

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

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./components/Home";

const App = () => {
    return (
        
            
                } />
            </Routes>
        </BrowserRouter>
    );
};

export default App;

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

cd client
mkdir components
cd components
touch Home.js

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

import React, { useState } from "react";

const Home = () => {
    const [message, setMessage] = useState("");
    const [subscriber, setSubscriber] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ message, subscriber });
        setMessage("");
        setSubscriber("");
    };

    return (
        
            
                Notify</h2>
            </nav>
            
                Send notifications to your users</h3>
                
                    Notification Title</label>
                     setMessage(e.target.value)}
                        placeholder='Let the user know that'
                    />
                    Subscribers</label>

                     setSubscriber(e.target.value)}
                    >
                        Select</option>
                    </select>
                    SEND NOTIFICATION</button>
                </form>
            </main>
        </div>
    );
};

export default Home;

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.

cd client
npx 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.

Now let's setup your account and send your first notification
\u2753 What is your application name? Devto Clone
\u2753 Now lets setup your environment. How would you like to proceed?
   > Create a free cloud account (Recommended)
\u2753 Create your account with:
   > Sign-in with GitHub
\u2753 I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy)
    > Yes
\u2714\ufe0f Create your account successfully.

We've created a demo web page for you to see novu notifications in action.
Visit: 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.

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

npm install @novu/notification-center

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

import {
    NovuProvider,
    PopoverNotificationCenter,
    NotificationBell,
} from "@novu/notification-center";
import { useNavigate } from "react-router-dom";

const Home = () => {
    const navigate = useNavigate();

    const onNotificationClick = (notification) => {
        navigate(notification.cta.data.url);
    };
    //...other statements

    return (
        
            
                Notify</h2>
                "}
                    applicationIdentifier={""}
                >
                    
                        {({ unseenCount }) => (
                            
                        )}
                    </PopoverNotificationCenter>
                </NovuProvider>
            </nav>
            ...</main>
        </div>
    );
};

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

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.

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

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.

{{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.

cd server
npm install @novu/node

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

//server/index.js

const { Novu } = require("@novu/node");
const novu = new Novu("");

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.

app.get("/subscribers", async (req, res) => {
    try {
        const { data } = await novu.subscribers.list(0);
        const resultData = data.data;
        //\ud83d\udc47\ud83c\udffb Returns subscibers with an id, and first and last names
        const subscribers = resultData.filter(
            (d) => d.firstName && d.lastName && d.subscriberId
        );
        res.json(subscribers);
    } catch (err) {
        console.error(err);
    }
});

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

//\ud83d\udc47\ud83c\udffb State representing the list of subscribers
const [subscribers, setSubscribers] = useState([
    { firstName: "", lastName: "", subscriberId: "Select", _id: "null" },
]);

//\ud83d\udc47\ud83c\udffb Fetch the list of subscribers on page load
useEffect(() => {
    async function fetchSubscribers() {
        try {
            const request = await fetch("http://localhost:4000/subscribers");
            const response = await request.json();
            setSubscribers([...subscribers, ...response]);
        } catch (err) {
            console.error(err);
        }
    }
    fetchSubscribers();
}, []);

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

setSubscriber(e.target.value)}
>
    {subscribers.map((s) => (
        {`${s.firstName} ${s.lastName} - ${s.subscriberId}`}</option>
    ))}
</select>

Generating the notifications from ChatGPT

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

app.post("/notify", (req, res) => {
    //\ud83d\udc47\ud83c\udffb Destructure the message and subscriber from the object
    const { message, subscriber } = req.body;
    //\ud83d\udc47\ud83c\udffb Separates the first name and the subscriber ID
    const subscriberDetails = subscriber.split(" ");
    const firstName = subscriberDetails[0];
    const subscriberId = subscriberDetails[3];
    //\ud83d\udc47\ud83c\udffb Added some specifications to the message to enable the AI generate a concise notification.
    const fullMessage = `I have a notification system and I want to send the user a notification about "${message}" can you write me one?
please use double curly brackets for variables.
make it short, and use only one variable for the user name.
Please just write 1 notification without any intro.`;

    //\ud83d\udc47\ud83c\udffb Log the required variables to the console
    console.log({ firstName, subscriberId, fullMessage });
});

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.

//\ud83d\udc47\ud83c\udffb Makes the POST request
async function sendNotification() {
    try {
        const request = await fetch("http://localhost:4000/notify", {
            method: "POST",
            body: JSON.stringify({
                message,
                subscriber,
            }),
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        const data = await request.json();
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}

//\ud83d\udc47\ud83c\udffb Runs when a user submits the form
const handleSubmit = (e) => {
    e.preventDefault();
    //\ud83d\udc47\ud83c\udffb Calls the function
    sendNotification();
    setMessage("");
    setSubscriber("");
};

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

app.post("/notify", (req, res) => {
    const { message, subscriber } = req.body;
    const subscriberDetails = subscriber.split(" ");
    const firstName = subscriberDetails[0];
    const subscriberId = subscriberDetails[3];
    const fullMessage = `I have a notification system and I want to send the user a notification about "${message}" can you write me one?
please use double curly brackets for variables.
make it short, and use only one variable for the user name.
Please just write 1 notification without any intro.`;
    console.log({ firstName, subscriberId, fullMessage });

    //\ud83d\udc47\ud83c\udffb Pass the variables as a parameter into the function
    chatgptFunction(fullMessage, subscriberId, firstName, res);
});

Create theĀ chatgptFunctionĀ as done below:

//\ud83d\udc47\ud83c\udffb Holds the AI-generated notification
let chatgptResult = "";

async function chatgptFunction(message, subscriberId, firstName, res) {
    // use puppeteer to bypass cloudflare (headful because of captchas)
    const api = new ChatGPTAPIBrowser({
        email: "",
        password: "",
    });
    //\ud83d\udc47\ud83c\udffb Open up the login screen on the browser
    await api.initSession();
    const result = await api.sendMessage(message);
    chatgptResult = result.response;
    //\ud83d\udc47\ud83c\udffb Replace the user variable with the user's first name
    const notificationString = chatgptResult.replace("{{user}}", firstName);

    console.log(notificationString, subscriberId);
}

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.

async function chatgptFunction(message, subscriberId, firstName, res) {
    // use puppeteer to bypass cloudflare (headful because of captchas)
    const api = new ChatGPTAPIBrowser({
        email: "",
        password: "",
    });
    await api.initSession();
    const result = await api.sendMessage(message);
    chatgptResult = result.response;
    const notificationString = chatgptResult.replace("{{user}}", firstName);

    //\ud83d\udc47\ud83c\udffb Pass the necessary variables as parameters
    sendNotification(notificationString, subscriberId, res);
}

//\ud83d\udc47\ud83c\udffb Sends the notification via Novu
async function sendNotification(data, subscriberId, res) {
    try {
        let result = await novu.trigger("", {
            to: {
                subscriberId: subscriberId,
            },
            payload: {
                message: data,
            },
        });
        return res.json({ message: result });
    } catch (err) {
        return res.json({ error_message: err });
    }
}

Congratulations!šŸŽ‰ You’ve completed the project for this tutorial.

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

Read More

You’re five minutes away from your first Novu-backed notification

Create a free account, send your first notification, all before your coffee gets cold... no credit card required.