Building a forum with React, NodeJS

Nevo David - Feb 27 '23 - - Dev Community

TL;DR

In this article, you'll learn how to build a forum system that allows users to create, react, and reply to post threads. In the end, we will also send a notification on each reply on a thread with Novu, you can skip the last step if you want only the technical stuff.

I know, there are no forums today like before, it's all about the Reddit, Facebook communities (and smaller ones like Devto and Mastodon), but! Once upon a time, when I was a boy, I was addicted to forums, I have actually created a few with PHPBB and vBulletin, back when PHP was a thing. being so nostalgic made me write this blog post 😎

A small request 🤗

I am trying to get Novu to 20k stars, can you help me out by starring the repository? it helps me to create more content every week.

https://github.com/novuhq/novu

Forum

Project Setup

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 forum-system
cd forum-system
mkdir client server


Enter fullscreen mode Exit fullscreen mode

Setting up the Node.js server

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



cd server & npm init -y


Enter fullscreen mode Exit fullscreen mode

Install Express, Nodemon, and the CORS library.



npm install express cors nodemon


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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.



//👇🏻index.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}`);
});


Enter fullscreen mode Exit fullscreen mode

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"
  },


Enter fullscreen mode Exit fullscreen mode

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



npm start


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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



npm install react-router-dom


Enter fullscreen mode Exit fullscreen mode

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 done below.



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


Enter fullscreen mode Exit fullscreen mode

Copy the CSS file required for styling the project here  into the src/index.css file.

Building the app user interface

Here, we'll create the user interface for the forum system to enable users to create, reply and react to various threads.

Create a components folder within the client/src folder containing the Home.js, Login.js, Nav.js, Register.js, and Replies.js files.



cd client/src
mkdir components
touch Home.js Login.js Nav.js Register.js Replies.js


Enter fullscreen mode Exit fullscreen mode
  • From the code snippet above:
    • The Login.js and Register.js files are the authentication pages of the web application.
    • The Home.js file represents the dashboard page shown after authentication. It allows users to create and react to the post threads.
    • The Replies.js file displays the response on each post and allows users to reply to the post thread.
    • The Nav.js is the navigation bar where we will configure Novu.

Update the App.js file to render the components using React Router.



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

const App = () => {
    return (
        <div>
            <BrowserRouter>
                <Routes>
                    <Route path='/' element={<Login />} />
                    <Route path='/register' element={<Register />} />
                    <Route path='/dashboard' element={<Home />} />
                    <Route path='/:id/replies' element={<Replies />} />
                </Routes>
            </BrowserRouter>
        </div>
    );
};

export default App;


Enter fullscreen mode Exit fullscreen mode

The Login page

Copy the code below into the Login.js file to render a form that accepts the user's email and password.



import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";

const Login = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ email, password });
        setEmail("");
        setPassword("");
    };

    return (
        <main className='login'>
            <h1 className='loginTitle'>Log into your account</h1>
            <form className='loginForm' onSubmit={handleSubmit}>
                <label htmlFor='email'>Email Address</label>
                <input
                    type='text'
                    name='email'
                    id='email'
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                />
                <label htmlFor='password'>Password</label>
                <input
                    type='password'
                    name='password'
                    id='password'
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                <button className='loginBtn'>SIGN IN</button>
                <p>
                    Don't have an account? <Link to='/register'>Create one</Link>
                </p>
            </form>
        </main>
    );
};
export default Login;


Enter fullscreen mode Exit fullscreen mode

Register

The Register page

Update the Register.js file to display the registration form that allows users to create an account using their email, username, and password.



import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";

const Register = () => {
    const [username, setUsername] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ username, email, password });
        setEmail("");
        setUsername("");
        setPassword("");
    };
    return (
        <main className='register'>
            <h1 className='registerTitle'>Create an account</h1>
            <form className='registerForm' onSubmit={handleSubmit}>
                <label htmlFor='username'>Username</label>
                <input
                    type='text'
                    name='username'
                    id='username'
                    required
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                />
                <label htmlFor='email'>Email Address</label>
                <input
                    type='text'
                    name='email'
                    id='email'
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                />
                <label htmlFor='password'>Password</label>
                <input
                    type='password'
                    name='password'
                    id='password'
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                <button className='registerBtn'>REGISTER</button>
                <p>
                    Have an account? <Link to='/'>Sign in</Link>
                </p>
            </form>
        </main>
    );
};

export default Register;


Enter fullscreen mode Exit fullscreen mode

Create an account

The Nav component

Update the Nav.js file to render a navigation bar that shows the application's title and a sign-out button. Later in this article, I'll guide you through adding Novu's notification bell within this component.



import React from "react";

const Nav = () => {
    const signOut = () => {
        alert("User signed out!");
    };
    return (
        <nav className='navbar'>
            <h2>Threadify</h2>
            <div className='navbarRight'>
                <button onClick={signOut}>Sign out</button>
            </div>
        </nav>
    );
};

export default Nav;


Enter fullscreen mode Exit fullscreen mode

The Home page

It is the home page after the user's authentication. They can create and react to posts (threads) within the Home component. Copy the code below into the Home.js file.



import React, { useState } from "react";
import Nav from "./Nav";

const Home = () => {
    const [thread, setThread] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ thread });
        setThread("");
    };
    return (
        <>
            <Nav />
            <main className='home'>
                <h2 className='homeTitle'>Create a Thread</h2>
                <form className='homeForm' onSubmit={handleSubmit}>
                    <div className='home__container'>
                        <label htmlFor='thread'>Title / Description</label>
                        <input
                            type='text'
                            name='thread'
                            required
                            value={thread}
                            onChange={(e) => setThread(e.target.value)}
                        />
                    </div>
                    <button className='homeBtn'>CREATE THREAD</button>
                </form>
            </main>
        </>
    );
};

export default Home;


Enter fullscreen mode Exit fullscreen mode

The code snippet above displays the navigation bar and an input field for the posts. We'll update the component in the upcoming sections.

Create a thread

The Replies page

This page is a dynamic route that allows users to reply and view comments on a post thread. Update the Replies.js file with the code snippet below:



import React, { useState } from "react";

const Replies = () => {
    const [reply, setReply] = useState("");

    const handleSubmitReply = (e) => {
        e.preventDefault();
        console.log({ reply });
        setReply("");
    };

    return (
        <main className='replies'>
            <form className='modal__content' onSubmit={handleSubmitReply}>
                <label htmlFor='reply'>Reply to the thread</label>
                <textarea
                    rows={5}
                    value={reply}
                    onChange={(e) => setReply(e.target.value)}
                    type='text'
                    name='reply'
                    className='modalInput'
                />

                <button className='modalBtn'>SEND</button>
            </form>
        </main>
    );
};

export default Replies;


Enter fullscreen mode Exit fullscreen mode

Congratulations! You've designed the application's user interface. Next, you'll learn how to register and log users into the application.

User authentication with React and Node.js

Here, I'll guide you through authenticating users and how to allow only authorised users to access protected pages within the web application.

PS: In a real-world application, passwords are hashed and saved in a secure database. For simplicity purposes, I'll store all the credentials in an array in this tutorial.

Creating new users

Add a POST route on the server that accepts the user's credentials - email, username, and password.



//👇🏻 holds all the existing users
const users = [];
//👇🏻 generates a random string as ID
const generateID = () => Math.random().toString(36).substring(2, 10);

app.post("/api/register", async (req, res) => {
    const { email, password, username } = req.body;
    //👇🏻 holds the ID
    const id = generateID();
    //👇🏻 logs all the user's credentials to the console.
    console.log({ email, password, username, id });
});


Enter fullscreen mode Exit fullscreen mode

Create a signUp function within the Register.js file that sends the user's credentials to the endpoint on the server.



const signUp = () => {
    fetch("http://localhost:4000/api/register", {
        method: "POST",
        body: JSON.stringify({
            email,
            password,
            username,
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            console.log(data);
        })
        .catch((err) => console.error(err));
};


Enter fullscreen mode Exit fullscreen mode

Call the function when a user submits the form as done below:



const handleSubmit = (e) => {
    e.preventDefault();
    //👇🏻 Triggers the function
    signUp();
    setEmail("");
    setUsername("");
    setPassword("");
};


Enter fullscreen mode Exit fullscreen mode

Update the /api/register route to save the user's credentials and return a response to the front-end.



app.post("/api/register", async (req, res) => {
    const { email, password, username } = req.body;
    const id = generateID();
    //👇🏻 ensures there is no existing user with the same credentials
    const result = users.filter(
        (user) => user.email === email && user.password === password
    );
    //👇🏻 if true
    if (result.length === 0) {
        const newUser = { id, email, password, username };
        //👇🏻 adds the user to the database (array)
        users.push(newUser);
        //👇🏻 returns a success message
        return res.json({
            message: "Account created successfully!",
        });
    }
    //👇🏻 if there is an existing user
    res.json({
        error_message: "User already exists",
    });
});


Enter fullscreen mode Exit fullscreen mode

The code snippet above accepts the user's credentials from the React.js application and checks if there is no existing user with the same credentials before saving the user to the database (array).

Finally, display the server’s response by updating the signUp function as done below.



//👇🏻 React Router's useNavigate hook
const navigate = useNavigate();

const signUp = () => {
    fetch("http://localhost:4000/api/register", {
        method: "POST",
        body: JSON.stringify({
            email,
            password,
            username,
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            if (data.error_message) {
                alert(data.error_message);
            } else {
                alert("Account created successfully!");
                navigate("/");
            }
        })
        .catch((err) => console.error(err));
};


Enter fullscreen mode Exit fullscreen mode

The code snippet above displays a success or error message from the Node.js server and redirects the user to the login page after successfully creating the account.

Logging users into the application

Add a POST route on the server that accepts the user's email and password and authenticates the users before granting them access to the web application.



app.post("/api/login", (req, res) => {
    const { email, password } = req.body;
    //👇🏻 checks if the user exists
    let result = users.filter(
        (user) => user.email === email && user.password === password
    );
    //👇🏻 if the user doesn't exist
    if (result.length !== 1) {
        return res.json({
            error_message: "Incorrect credentials",
        });
    }
    //👇🏻 Returns the id if successfuly logged in
    res.json({
        message: "Login successfully",
        id: result[0].id,
    });
});


Enter fullscreen mode Exit fullscreen mode

Create a loginUser function within the Login.js file that sends the user's email and password to the Node.js server.



//👇🏻 React Router's useNavigate hook
const navigate = useNavigate();

const loginUser = () => {
    fetch("http://localhost:4000/api/login", {
        method: "POST",
        body: JSON.stringify({
            email,
            password,
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            if (data.error_message) {
                alert(data.error_message);
            } else {
                alert(data.message);
                navigate("/dashboard");
                localStorage.setItem("_id", data.id);
            }
        })
        .catch((err) => console.error(err));
};


Enter fullscreen mode Exit fullscreen mode

The code snippet above sends the user's credentials to the Node.js server and displays the response on the front end. The application redirects authenticated users to the Home component and saves their id to the local storage for easy identification.

Update the signOut function within the Nav.js file to remove the id from the local storage when a user logs out.



const signOut = () => {
    localStorage.removeItem("_id");
    //👇🏻 redirects to the login page
    navigate("/");
};


Enter fullscreen mode Exit fullscreen mode

Creating and retrieving post threads within the application

Here, you'll learn how to create and retrieve the posts from the Node.js server.

Add a POST route within the index.js file that accepts the post title and the user's id from the React.js application.



app.post("/api/create/thread", async (req, res) => {
    const { thread, userId } = req.body;
    const threadId = generateID();

    console.log({ thread, userId, threadId });
});


Enter fullscreen mode Exit fullscreen mode

Next, send the user's id and the post title to the server. Before then, let's ensure the Home.js route is protected. Add a useEffect hook within the Home component to determine whether the user is authenticated.



import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

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

    //👇🏻 The useEffect Hook
    useEffect(() => {
        const checkUser = () => {
            if (!localStorage.getItem("_id")) {
                navigate("/");
            } else {
                console.log("Authenticated");
            }
        };
        checkUser();
    }, [navigate]);

    return <>{/*--the UI elements*/}</>;
};


Enter fullscreen mode Exit fullscreen mode

When users sign in to the application, we save their id to the local storage for easy identification. The code snippet above checks if the id exists; otherwise, the user is redirected to the login page.

Add a function within the Home component that sends the user’s id and the post title to the Node.js server when the form is submitted.



const createThread = () => {
    fetch("http://localhost:4000/api/create/thread", {
        method: "POST",
        body: JSON.stringify({
            thread,
            userId: localStorage.getItem("_id"),
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            console.log(data);
        })
        .catch((err) => console.error(err));
};

//👇🏻 Triggered when the form is submitted
const handleSubmit = (e) => {
    e.preventDefault();
    //👇🏻 Calls the function
    createThread();
    setThread("");
};


Enter fullscreen mode Exit fullscreen mode

Save the post and send all the available posts to the client for display.



//👇🏻 holds all the posts created
const threadList = [];

app.post("/api/create/thread", async (req, res) => {
const { thread, userId } = req.body;
const threadId = generateID();

    //👇🏻 add post details to the array
    threadList.unshift({
        id: threadId,
        title: thread,
        userId,
        replies: [],
        likes: [],
    });

    //👇🏻 Returns a response containing the posts
    res.json({
        message: "Thread created successfully!",
        threads: threadList,
    });
});


Enter fullscreen mode Exit fullscreen mode

The code snippet above accepts the user's id and post title from the front end. Then, save an object that holds the post details and returns a response containing all the saved posts.

Displaying the post threads

Create a state that will hold all the posts within the Home component.



const [threadList, setThreadList] = useState([]);


Enter fullscreen mode Exit fullscreen mode

Update the createThread function as done below:



const createThread = () => {
    fetch("http://localhost:4000/api/create/thread", {
        method: "POST",
        body: JSON.stringify({
            thread,
            userId: localStorage.getItem("_id"),
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            alert(data.message);
            setThreadList(data.threads);
        })
        .catch((err) => console.error(err));
};


Enter fullscreen mode Exit fullscreen mode

The createThread function retrieves all the posts available within the application and saves them into the threadList state.

Update the Home.js file to display the available posts as done below:



return (
    <>
        <Nav />
        <main className='home'>
            <h2 className='homeTitle'>Create a Thread</h2>
            <form className='homeForm' onSubmit={handleSubmit}>
                {/*--form UI elements--*/}
            </form>

            <div className='thread__container'>
                {threadList.map((thread) => (
                    <div className='thread__item' key={thread.id}>
                        <p>{thread.title}</p>
                        <div className='react__container'>
                            <Likes numberOfLikes={thread.likes.length} threadId={thread.id} />
                            <Comments
                                numberOfComments={thread.replies.length}
                                threadId={thread.id}
                                title={thread.title}
                            />
                        </div>
                    </div>
                ))}
            </div>
        </main>
    </>
);


Enter fullscreen mode Exit fullscreen mode
  • From the code snippet above:
    • All the posts are displayed within the Home component.
    • I added two new components - Likes and Comments. They both contain SVG icons from Heroicons.
    • The Likes component accepts the post id and the number of likes on a post - length of the likes array on each post.
    • The Comments component accepts the length of the replies array, the post id, and its title.

Create a thread

Create a utils folder containing both components.



cd client/src
mkdir utils
touch Likes.js Comments.js


Enter fullscreen mode Exit fullscreen mode

Copy the code below into the Likes.js file.



import React from "react";

const Likes = ({ numberOfLikes, threadId }) => {
    return (
        <div className='likes__container'>
            <svg
                xmlns='http://www.w3.org/2000/svg'
                viewBox='0 0 24 24'
                fill='currentColor'
                className='w-4 h-4 likesBtn'
            >
                <path d='M7.493 18.75c-.425 0-.82-.236-.975-.632A7.48 7.48 0 016 15.375c0-1.75.599-3.358 1.602-4.634.151-.192.373-.309.6-.397.473-.183.89-.514 1.212-.924a9.042 9.042 0 012.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 00.322-1.672V3a.75.75 0 01.75-.75 2.25 2.25 0 012.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 01-2.649 7.521c-.388.482-.987.729-1.605.729H14.23c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 00-1.423-.23h-.777zM2.331 10.977a11.969 11.969 0 00-.831 4.398 12 12 0 00.52 3.507c.26.85 1.084 1.368 1.973 1.368H4.9c.445 0 .72-.498.523-.898a8.963 8.963 0 01-.924-3.977c0-1.708.476-3.305 1.302-4.666.245-.403-.028-.959-.5-.959H4.25c-.832 0-1.612.453-1.918 1.227z' />
            </svg>
            <p style={{ color: "#434242" }}>
                {numberOfLikes === 0 ? "" : numberOfLikes}
            </p>
        </div>
    );
};

export default Likes;


Enter fullscreen mode Exit fullscreen mode

The code snippet above contains the SVG element for displaying the Like icon. The component also renders the number of likes on a post.

Copy the code below into the Comments.js file.



import React from "react";
import { useNavigate } from "react-router-dom";

const Comments = ({ numberOfComments, threadId }) => {
    const navigate = useNavigate();

    const handleAddComment = () => {
        navigate(`/${threadId}/replies`);
    };

    return (
        <div className='likes__container'>
            <svg
                xmlns='http://www.w3.org/2000/svg'
                viewBox='0 0 24 24'
                fill='currentColor'
                className='w-6 h-6 likesBtn'
                onClick={handleAddComment}
            >
                <path
                    fillRule='evenodd'
                    d='M4.804 21.644A6.707 6.707 0 006 21.75a6.721 6.721 0 003.583-1.029c.774.182 1.584.279 2.417.279 5.322 0 9.75-3.97 9.75-9 0-5.03-4.428-9-9.75-9s-9.75 3.97-9.75 9c0 2.409 1.025 4.587 2.674 6.192.232.226.277.428.254.543a3.73 3.73 0 01-.814 1.686.75.75 0 00.44 1.223zM8.25 10.875a1.125 1.125 0 100 2.25 1.125 1.125 0 000-2.25zM10.875 12a1.125 1.125 0 112.25 0 1.125 1.125 0 01-2.25 0zm4.875-1.125a1.125 1.125 0 100 2.25 1.125 1.125 0 000-2.25z'
                    clipRule='evenodd'
                />
            </svg>
            <p style={{ color: "#434242" }}>
                {numberOfComments === 0 ? "" : numberOfComments}
            </p>
        </div>
    );
};

export default Comments;


Enter fullscreen mode Exit fullscreen mode

The code snippet contains the SVG element for the Comments button and the number of comments on the post.
The handleAddComment function is triggered when a user clicks the comment icon. It redirects the user to the Replies component where they can view and add to the replies on each post.

So far, we've been able to display the available posts only when we create a new post. Next, let's retrieve them when the component is mounted.

Add a GET route on the server that returns all the posts.



app.get("/api/all/threads", (req, res) => {
    res.json({
        threads: threadList,
    });
});


Enter fullscreen mode Exit fullscreen mode

Update the useEffect hook within the Home component to fetch all the posts from the server.



useEffect(() => {
    const checkUser = () => {
        if (!localStorage.getItem("_id")) {
            navigate("/");
        } else {
            fetch("http://localhost:4000/api/all/threads")
                .then((res) => res.json())
                .then((data) => setThreadList(data.threads))
                .catch((err) => console.error(err));
        }
    };
    checkUser();
}, [navigate]);


Enter fullscreen mode Exit fullscreen mode

Congratulations on making it this far! Next, you'll learn how to react and reply to the posts.

How to react and reply to each posts

In this section, you'll learn how to react and reply to each post. Users will be able to drop a like or comment on each post.

Reacting to each post

Create a function within the Likes.js file that runs when a user clicks on the Like icon.



const Likes = ({ numberOfLikes, threadId }) => {
    const handleLikeFunction = () => {
        alert("You just liked the post!");
    };

    return (
        <div className='likes__container'>
            <svg
                xmlns='http://www.w3.org/2000/svg'
                viewBox='0 0 24 24'
                fill='currentColor'
                className='w-4 h-4 likesBtn'
                onClick={handleLikeFunction}
            >
                {/*--other UI elements*/}
            </svg>
        </div>
    );
};


Enter fullscreen mode Exit fullscreen mode

Create a POST route on the server that validates the reaction.



app.post("/api/thread/like", (req, res) => {
    //👇🏻 accepts the post id and the user id
    const { threadId, userId } = req.body;
    //👇🏻 gets the reacted post
    const result = threadList.filter((thread) => thread.id === threadId);
    //👇🏻 gets the likes property
    const threadLikes = result[0].likes;
    //👇🏻 authenticates the reaction
    const authenticateReaction = threadLikes.filter((user) => user === userId);
    //👇🏻 adds the users to the likes array
    if (authenticateReaction.length === 0) {
        threadLikes.push(userId);
        return res.json({
            message: "You've reacted to the post!",
        });
    }
    //👇🏻 Returns an error user has reacted to the post earlier
    res.json({
        error_message: "You can only react once!",
    });
});


Enter fullscreen mode Exit fullscreen mode
  • From the code snippet above:
    • The route accepts the post id and the user's id from the React.js application and searches for the post that received a reaction.
    • Then, validates the reaction before adding the user to the likes array.

Update the handleLikeFunction to send a POST request to the api/thread/like endpoint whenever a user reacts to the post.



const handleLikeFunction = () => {
    fetch("http://localhost:4000/api/thread/like", {
        method: "POST",
        body: JSON.stringify({
            threadId,
            userId: localStorage.getItem("_id"),
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            if (data.error_message) {
                alert(data.error_message);
            } else {
                alert(data.message);
            }
        })
        .catch((err) => console.error(err));
};


Enter fullscreen mode Exit fullscreen mode

Displaying the replies on each post

Here, I'll guide you through displaying the replies on each post within the React app.

Add a POST route on the server that accepts a post ID from the front end and returns the title and all the responses under such post.



app.post("/api/thread/replies", (req, res) => {
    //👇🏻 The post ID
    const { id } = req.body;
    //👇🏻 searches for the post
    const result = threadList.filter((thread) => thread.id === id);
    //👇🏻 return the title and replies
    res.json({
        replies: result[0].replies,
        title: result[0].title,
    });
});


Enter fullscreen mode Exit fullscreen mode

Next, update the Replies component to send a request to the api/thread/replies endpoint on the server and display the title and replies when the page loads.



import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";

const Replies = () => {
    const [replyList, setReplyList] = useState([]);
    const [reply, setReply] = useState("");
    const [title, setTitle] = useState("");
    const navigate = useNavigate();
    const { id } = useParams();

    useEffect(() => {
        const fetchReplies = () => {
            fetch("http://localhost:4000/api/thread/replies", {
                method: "POST",
                body: JSON.stringify({
                    id,
                }),
                headers: {
                    "Content-Type": "application/json",
                },
            })
                .then((res) => res.json())
                .then((data) => {
                    setReplyList(data.replies);
                    setTitle(data.title);
                })
                .catch((err) => console.error(err));
        };
        fetchReplies();
    }, [id]);

    //👇🏻 This function when triggered when we add a new reply
    const handleSubmitReply = (e) => {
        e.preventDefault();
        console.log({ reply });
        setReply("");
    };
    return <main className='replies'>{/*--UI elements--*/}</main>;
};


Enter fullscreen mode Exit fullscreen mode
  • From the code snippet above:
    • The useEffect hook sends a request to the server's endpoint and retrieves the post title and its replies.
    • The title and replyList states hold both the title and replies respectively.
    • The variable id holds the post ID retrieved from the URL via dynamic routing in React Router.

Display the replies on each post as done below:



return (
    <main className='replies'>
        <h1 className='repliesTitle'>{title}</h1>

        <form className='modal__content' onSubmit={handleSubmitReply}>
            <label htmlFor='reply'>Reply to the thread</label>
            <textarea
                rows={5}
                value={reply}
                onChange={(e) => setReply(e.target.value)}
                type='text'
                name='reply'
                className='modalInput'
            />

            <button className='modalBtn'>SEND</button>
        </form>

        <div className='thread__container'>
            {replyList.map((reply) => (
                <div className='thread__item'>
                    <p>{reply.text}</p>
                    <div className='react__container'>
                        <p style={{ opacity: "0.5" }}>by {reply.name}</p>
                    </div>
                </div>
            ))}
        </div>
    </main>
);


Enter fullscreen mode Exit fullscreen mode

The code snippet above shows the layout of the Replies component displaying the post title, replies, and a form field for replying to a post.

Reply

Creating the post reply functionality

Create an endpoint on the server that allows users to add new replies as done below:



app.post("/api/create/reply", async (req, res) => {
    //👇🏻 accepts the post id, user id, and reply
    const { id, userId, reply } = req.body;
    //👇🏻 search for the exact post that was replied to
    const result = threadList.filter((thread) => thread.id === id);
    //👇🏻 search for the user via its id
    const user = users.filter((user) => user.id === userId);
    //👇🏻 saves the user name and reply
    result[0].replies.unshift({
        userId: user[0].id,
        name: user[0].username,
        text: reply,
    });

    res.json({
        message: "Response added successfully!",
    });
});


Enter fullscreen mode Exit fullscreen mode

The code snippet above accepts the post id, user id, and reply from the React app, searches for the post via its ID, and adds the user's id, username, and reply to the post replies.

Create a function that sends a request to the /api/create/reply endpoint.



const addReply = () => {
    fetch("http://localhost:4000/api/create/reply", {
        method: "POST",
        body: JSON.stringify({
            id,
            userId: localStorage.getItem("_id"),
            reply,
        }),
        headers: {
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((data) => {
            alert(data.message);
            navigate("/dashboard");
        })
        .catch((err) => console.error(err));
};

const handleSubmitReply = (e) => {
    e.preventDefault();
    //👇🏻 calls the function
    addReply();
    setReply("");
};


Enter fullscreen mode Exit fullscreen mode

Congratulations on making it thus far! In the upcoming sections, you'll learn how to send notifications to multiple users using the Topics API provided by Novu.

How to send notifications via the Topic API in Novu

In this section, we'll use the Novu Topic API to send notifications to multiple users simultaneously. To do this, the API allows us to create a unique topic, assign subscribers to the topic, and send a bulk notification to the subscribers at once.

Setting up your Novu admin panel

Navigate into the client folder and create a Novu project by running the code below.



cd client
npx novu init


Enter fullscreen mode Exit fullscreen mode

Select your application name and sign in to Novu. 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
? What is your application name? Forum App
? Now lets setup your environment. How would you like to proceed? Create a free cloud account (Recommended)
? Create your account with: Sign-in with GitHub
? I accept the Terms and Conditions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy) Yes
✔ Created your account successfully.

  We've created a demo web page for you to see novu notifications in action.
  Visit: http://localhost:51422/demo to continue


Enter fullscreen mode Exit fullscreen mode

Visit the demo page, copy your subscriber ID from the page, and click the Skip Tutorial button.

Notification Template

Create a notification template with a workflow as shown below:

Update In-app

Update the In-App notification template to send this message to the post creator when there is a new reply.



Someone just dropped a reply to the thread!


Enter fullscreen mode Exit fullscreen mode

Install the Novu Notification package within your React project.



npm install @novu/notification-center


Enter fullscreen mode Exit fullscreen mode

Update the components/Nav.js file to contain the Novu notification bell according to its documentation.



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

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

    const onNotificationClick = (notification) =>
        navigate(notification.cta.data.url);

    const signOut = () => {
        localStorage.removeItem("_id");
        navigate("/");
    };
    return (
        <nav className='navbar'>
            <h2>Threadify</h2>

            <div className='navbarRight'>
                <NovuProvider
                    subscriberId='<YOUR_SUBSCRIBER_ID>'
                    applicationIdentifier='<YOUR_APP_ID>'
                >
                    <PopoverNotificationCenter
                        onNotificationClick={onNotificationClick}
                        colorScheme='light'
                    >
                        {({ unseenCount }) => (
                            <NotificationBell unseenCount={unseenCount} />
                        )}
                    </PopoverNotificationCenter>
                </NovuProvider>

                <button onClick={signOut}>Sign out</button>
            </div>
        </nav>
    );
};


Enter fullscreen mode Exit fullscreen mode

The code snippet above adds Novu's notification bell icon to the Nav component, enabling us to view all the notifications in our app. Replace the Subscriber ID variable with yours.

bar

Select Settings on your Novu Admin Panel and copy your App ID and API key. Ensure you add the App ID into its variable within the Nav.js file.

Configuring Novu on the server

Install the Novu SDK for Node.js into the server folder.



npm install @novu/node


Enter fullscreen mode Exit fullscreen mode

Import Novu from the package and create an instance using your API Key. Replace the API Key variable with your API key copied earlier.



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


Enter fullscreen mode Exit fullscreen mode

Sending notifications via the Novu Topic API

To begin with, you'll need to add the users as subscribers when they login to the application. Therefore, update the /api/register route to add the user as a Novu subscriber.



app.post("/api/register", async (req, res) => {
    const { email, password, username } = req.body;
    const id = generateID();
    const result = users.filter(
        (user) => user.email === email && user.password === password
    );

    if (result.length === 0) {
        const newUser = { id, email, password, username };
        //👇🏻 add the user as a subscriber
        await novu.subscribers.identify(id, { email: email });

        users.push(newUser);
        return res.json({
            message: "Account created successfully!",
        });
    }
    res.json({
        error_message: "User already exists",
    });
});


Enter fullscreen mode Exit fullscreen mode

The code snippet above creates a Novu subscriber via the user’s email and id.

Next, add each new post as a Novu topic and add the user as a subscriber to the topic.



app.post("/api/create/thread", async (req, res) => {
    const { thread, userId } = req.body;
    let threadId = generateID();
    threadList.unshift({
        id: threadId,
        title: thread,
        userId,
        replies: [],
        likes: [],
    });
//👇🏻 creates a new topic from the post 
    await novu.topics.create({
        key: threadId,
        name: thread,
    });
//👇🏻 add the user as a subscriber
    await novu.topics.addSubscribers(threadId, {
        subscribers: [userId],
        //replace with your subscriber ID to test run
        // subscribers: ["<YOUR_SUBSCRIBER_ID>"],
    });

    res.json({
        message: "Thread created successfully!",
        threads: threadList,
    });
});


Enter fullscreen mode Exit fullscreen mode

Finally, send notifications to the subscriber when there is a new response on the thread



app.post("/api/create/reply", async (req, res) => {
    const { id, userId, reply } = req.body;
    const result = threadList.filter((thread) => thread.id === id);
    const user = users.filter((user) => user.id === userId);
    result[0].replies.unshift({ name: user[0].username, text: reply });
//👇🏻 Triggers the function when there is a new reply
    await novu.trigger("topicnotification", {
        to: [{ type: "Topic", topicKey: id }],
    });

    res.json({
        message: "Response added successfully!",
    });
});


Enter fullscreen mode Exit fullscreen mode

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

Final

Conclusion

So far, you've learnt how to authenticate users, communicate between a React and Node.js app, and send bulk notifications using the Novu Topic API.

Novu is an open-source notification infrastructure that enables you to send SMS, chat, push, and e-mail notifications from a single dashboard. The Topic API is just one of the exciting features Novu provides; feel free to learn more about us here.

The source code for this tutorial is available here:

https://github.com/novuhq/blog/tree/main/forum-system-with-react-novu-node

Thank you for reading!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .