
This Apress imprint is published by the registered company APress Media, LLC part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.
is a full-stack JavaScript developer who has been working in the IT industry for the past 16 years. He has worked for some of the world’s top development firms and investment banks. Nabendu is a tech blogger who publishes on DEV Community (dev.to), Medium (medium.com), and The Web Dev(TWD) (thewebdev.tech). He is an all-around nerd who is passionate about everything JavaScript, React, and Gatsby. You can find him on Twitter @nabendu82.
is a self-taught software engineer with experience in back-end and full-stack engineering. With experience spanning more than four years, he loves to solve problems at scale. Currently, he is interested in startups, open source web development, and distributed systems. In his spare time, Alexander loves watching soccer and listening to all genres of music.
Welcome to MERN Projects for Beginners, where you learn to build awesome web apps using the MERN (MongoDB, Express, React, Node.js) framework. This stack is in high demand in the startup sector because you can make a fully functional web app using it. A front-end engineer who knows HTML, CSS, and React can quickly learn Node.js and MongoDB and build a fully production-ready web app.
In this book, you learn how to host a back end using Node.js code in Heroku. The front-end site uses React code and Firebase hosting. It is also hosted through a cloud database called MongoDB Atlas. Most of the hosting setups are the same in the next five chapters, so it won’t be repeated in most chapters.
MongoDB is an open source document based on the NoSQL database. It is different from traditional relational databases that store data in tables. It stores data in JSON-like documents. It is highly scalable and performance-oriented and thus suited for modern-day web apps.
React is the most popular open source JavaScript library for building a website’s or web app’s front end or user interface. It is developed and maintained by Facebook.
Node.js lets developers write server-side code using JavaScript. It integrates very well with React or Angular at the front end and with MongoDB for databases.
Express is a framework of Node.js, and through it, you can create API endpoints, which are the basis of any back-end server-side code.

Firebase console caption

App name

Project created
MongoDB is the database that you work with on the cloud. It is also known as MongoDB Atlas. This is easier to work with than setting up on a local machine. Go to www.mongodb.com and log in or create a new account.

MongoDB new project

Project name

MongoDB Create Project

Build a Cluster

Choose region

Cluster created

Create database user

Add user

Network access

Allow access

Connect your application

Connection string

Heroku login

Heroku app name

Heroku instructions
Run the heroku login command in the backend folder. You are asked for permission to open the browser. This command asks you to press any key to open in the browser.

Figure 1-22.

Close popup

Open back-end app

Configure

Existing project

Correct project

Build
Next, run npm run build in the frontend folder for an optimal production build. The final command, firebase deploy, deploys the project to Firebase. If successful, the site is now live, which is shown in upcoming chapters.
Let’s go over installing Node.js and npm (node package manager) if they are not already installed on your system. Most of the code in this book requires Node.js and npm. The React front-end code also requires Node.js. Through npm, you can install many small open sourced programs, which adds functionality to both React and Node.js.
When you install Node.js, npm is also automatically installed on your system. The following instructions are for a Windows-based system, although macOS users can find a similar guide on the Internet.

Node.js installer

Run button

Node.js welcome

Agreement

Installation location

Default packages

Dependencies
In this chapter, we have learnt about all the different technologies to create a MERN(MongoDB, Express, ReactJS, NodeJS) project. We have also learnt how to deploy them in different environments and we will be using them in the next chapters.
Welcome to Chapter 2, where you build a dating app using the MERN (MongoDB, Express, React, Node.js) framework. The back end is hosted in Heroku, and the front-end site uses Firebase hosting. The icons in the project come from Material-UI.

Finished app
Since the front-end site is hosted through Firebase, let’s create the basic setting while create-react-app creates the React app. Following the same setup instructions in Chapter 1, I created dating-app-mern in the Firebase console.

Delete files

Initial app
Next, create a components folder inside the src folder. Create two files—Header.js and Header.css—inside the components folder. Header.js has three things: a person icon, a logo, and a forum icon. The logo is taken from the project’s public directory, which contains the React logo by default.

Header component
Next, put the content in DatingCards.js. Here, inside a people state variable, you store the name and images of four people. Next, import DatingCard and use it as a component. Here, you use the props mentioned in the react-tinder-card documentation.

All people

Images appear

Almost complete
Let’s now create the SwipeButtons component , which are the buttons in the footer. These buttons add to the app’s styling. They won’t be functional since it’s a simple app. Create two files—SwipeButtons.js and SwipeButtons.css—inside the components folder. You also need to include it in the App.js file.
Next, style the buttons in the SwipeButtons.css file. First, style the swipeButtons class and make it flex with position: fixed. In a fixed position, an element remains attached where stated (at the bottom in this case), even as the user scrolls. You are also styling the MuiIconButton-root class, which was created by the package.

Front end complete

Back-end initial setup
Next, open package.json. The line "type": "module" is required to have React-like imports enabled in Node.js. These modules are known as ECMA modules. The initial modules with require statements are known as CommonJS modules. You can read more about it at https://blog.logrocket.com/how-to-use-ecmascript-modules-with-node-js/.
The MongoDB setup is the same as described in Chapter 1. You need to follow it and create a new project named dating-app-mern.
Let’s create the initial route, which generally checks whether everything is set up correctly. The Express package in Node.js allows you to create routes, which is how most of the Internet works. Most back-end languages like Node.js, Java offer capabilities to create these routes, which interact with the databases. The initial route doesn’t interact with the database and simply returns a text when you go to it, using a GET request. Create a server.js file in the dating-app-backend folder. Here, you import the Express and the Mongoose packages first. Next, use Express to create a port variable to run on port 8001.
The first API endpoint is a simple GET request created by app.get(), which shows Hello TheWebDev text if successful.

Initial route
In MongoDB, you need to create a database user and provide network access. The process is the same as in Chapter 1. Follow those instructions and get the user credentials and connection URL.
MongoDB stores data in a JSON format instead of the regular table structure found in a traditional database like Oracle. You create the schema file required by MongoDB. It tells you how fields are stored in MongoDB.
You now use the schema to create the endpoint that adds data to the database. The MVC pattern is followed here; it is the traditional flow of a web application. Read more about it at https://medium.com/createdd-notes/understanding-mvc-architecture-with-react-6cd38e91fefd.
Next, use a POST request that takes any data from the user and sends it to the database. You can use any endpoint. For example, if you write an article on Facebook and hit the POST button, your article is saved in the Facebook database once the POST request is made.
The GET endpoints fetch all the data from the database. Again, you can give any endpoint. For example, when you browse through the feed in Facebook, a GET request is sent to the endpoint, which in turn fetches all posts from the Facebook database.
In server.js, create a POST request to the /dating/cards endpoint. The load is in req.body to MongoDB. Then you use create() to send dbCard. If it’s a success, you receive status 201; otherwise, you receive status 500. The updated content is marked in bold.
To check the routes, let’s use the Postman app. Download and install it.

Initial route check
Before moving forward with the POST request, you need to complete two things. First, implement CORS; otherwise, you get cross-origin errors later when you deploy the app. CORS (Cross-Origin Resource Sharing) is the mechanism that restricts access from one domain to another. Suppose you are on http://example.com and want to access http://mybank.com/accountdetails. CORS won’t allow you to do so. It is only allowed if http://mybank.com allows cross-origin sharing with http://example.com.
In server.js, import CORS and use it in with app.use(). You also need to use the express.json() middleware. It is required because you need it to parse the incoming JSON object from MongoDB to read the body.
In Postman, change the request to POST, and then add the http://localhost:8001/dating/cards endpoint.
Next, click Body and select raw. Select JSON(application/json) from the drop-down menu. In the text editor, copy the data from DatingCards.js file. Make the data JSON by adding double quotes to the keys.

POST route

GET route

App complete
Go to www.heroku.com to deploy the back end. You followed the same procedure in Chapter 1 to create an app named dating-mern-backend.
In this chapter, we have created a dating app in MERN stack. We build the frontend in ReactJS and hosted it in Firebase. The backend was build in NodeJS and hosted in Heroku. The database was build in MongoDB.
Welcome to your next MERN project, where you build an awesome short video app using the MERN (MongoDB, Express, React, Node.js) framework. On the back end, it is hosted in Heroku, and the front-end site uses Firebase hosting. Material-UI (https://material-ui.com) supplies the icons in the project.

Deployed version
Since the front-end site is hosted through Firebase, you can create the basic setting while create-react-app creates the React app. Following the setup instructions in Chapter 1, I created short-video-mern in the Firebase console.
The deleting of the files and basic setup in index.js, App.js, and App.css is like what was done in Chapter 2. Follow those instructions.

Initial app
Next, create a components folder inside the src folder. Create two files—Video.js and Video.css—inside the components folder. In the Video.js file, add a video tag and a vertical video link. I used the link to my YouTube short video on my channel.

Video shown

Snap feature
Right now, the videos won’t play. To make them play, you must use a reference (or ref). React works on a virtual DOM. Generally, you only need to access the DOM (Document Object Model) in special cases, and you use refs to access DOM elements. In this case, you need to access the <video> HTML element so that you can access the play() and pause() properties, which are only available through refs.
First, import the useRef and useState hooks to get the videoRef variable, which is used inside the video element, where you create an onClick handler to fire a handleVideoPress function.
Inside the handleVideoPress function , use the playing state variable to check if the video plays, and then set it to pause with videoRef.current.pause() and change the playing state to false. You do the reverse in the else block.
Click the video to play it on localhost. Click it again to pause.
Let’s work on the second component, which shows the username, video title, and a rolling ticker in the video’s footer.

Initial footer
It’s time to use it in the VideoFooter.js file. Include the music note icon, MusicNoteIcon, inside the videoFooter__ticker div, which you imported from Material-UI.
Next, include the ticker as per the documentation and a record (or rotating disc) image in the VideoFooter.js file. As you can see at the bottom of the news channels, the ticker is moving text across the screen. A record/rotating disc image is also shown, to which you add nice animations very shortly.
Next, add styles for both the ticker and the recorded image in the VideoFooter.css file. Here, you align the ticker with the music icon and add animation to move the recorded image.

Footer complete
Let’s now create a sidebar component, which shows icons on the right side of the video.

Sidebar completed
All the data from the App.js file is passed to child components. You make the components dynamic so that you can pass props to them. Like in React, you pass data from a parent component to a child component with props. The video sidebar is the first component to work on. In VideoSidebar.js, pass the numbers as props.
Similarly, pass the strings as props in the VideoFooter.js file.
You want to further drill the props from the app component to have different video files. Let’s add these props to the Video.js file and use them.
In App.js, you pass all the props and can pass two different videos.
The front end is complete, and it’s time to start the back end.

Initial server setup
Next, open package.json. The line "type" : "module" is required to have React-like imports enabled in Node.js. Include a start script to run the server.js file.
The MongoDB setup is the same as described in Chapter 1. Follow those instructions and create a new project named short-video-mern.
Next, create a server.js file in the short-video-backend folder. Here, you import the Express and Mongoose packages. Then use Express to create a port variable to run on port 9000.
The first API endpoint is a simple GET request created by app.get(), which shows the text Hello TheWebDev if successful.

localhost
In MongoDB, you need to create a database user and give network access. The process is the same as explained in Chapter 1. Follow those instructions, and then get the user credentials and connection URL.
In server.js, create a connection_url variable and paste the URL within the string from MongoDB. You need to provide the password that you saved earlier and a database name.
Next, let’s create the schema file required by MongoDB. It tells you about the way fields are stored in MongoDB. Create a dbModel.js file inside the short-video-backend folder.
You can now use the schema to create the endpoint that adds data to the database.
In server.js, create a POST request to the /v2/posts endpoint. The load is in req.body to MongoDB. Then use create() to send dbVideos. If it’s a success, you receive status 201; otherwise, you receive status 500.
Next, create the GET endpoint to /v2/posts to get the data from the database. You are using find() here. You receive status 200 if successful (otherwise, status 500).

Get request
In server.js, import CORS and then use it with app.use(). You also need to use the express.json() middleware.
In Postman, change the request to POST and then add the http://localhost:9000/v2/posts endpoint.
Next, click Body and select raw. Select JSON(application/json) from the drop-down menu. In the text editor, copy the data from the App.js file. Make the data JSON by adding double quotes to the keys.

Success Message POST

Success Message GET
In App.js, import the local axios. Then use the useEffect hook to do the API call to /v2/posts endpoint. Once you receive the data, store it in the videos state variable using setVideos().
In the return statement, get rid of the hard-coded stuff. After that, map through the videos array and pass the props to the video component.

Figure 3-13.
Go to www.heroku.com to deploy the back end. Follow the same procedure that you did in Chapter 1 and create an app named short-video-backend.

Figure 3-14.
In this chapter, we have created a short video sharing app. We build the frontend in ReactJS and hosted it in Firebase. The backend was build in NodeJS and hosted in Heroku. The database was build in MongoDB.
Welcome to your third MERN project, where you build an awesome messaging app using the MERN framework. The back end is hosted in Heroku, and the front-end site is hosted in Firebase.

Final hosted app
Since the front-end site is hosted through Firebase, you can create the basic setting while create-react-app creates the React app. Following the setup instructions from Chapter 1, I created messaging-app-mern in the Firebase console.
The deleting of the files and basic setup in index.js, App.js, and App.css is like what was done in Chapter 2. Follow those instructions.

Initial app

Initial background
Figure 4-4 shows the aligned icons on localhost.

Icons aligned
I used an image from my Twitter account as the avatar. The updated content is marked in bold.

Search bar

Sidebar chat

Chat component
Next, go back to the Chat.js file and put the hard-coded message in a p tag in the chat__message class. Two span tags are used for the name and timestamp.

Chat messages

Footer complete

Initial back-end setup
The MongoDB setup is the same as described in Chapter 1. Follow those instructions and create a new project named messaging-app-mern.
Create a server.js file in the messaging-app-backend folder, where you import the Express and Mongoose packages. Then use Express to create a port variable to run on port 9000.
The first API endpoint is a simple GET request created by app.get(), which shows the text Hello TheWebDev if successful.
Then, listen on port with app.listen().
import express from 'express'
import mongoose from 'mongoose'

Initial route
In MongoDB, you need to create a database user and give network access. The process is the same as explained in Chapter 1. Follow those instructions, and then get the user credentials and connection URL.
In the server.js file, create a connection_url variable and paste the URL within the string from MongoDB. You need to provide the password that you saved earlier and a database name.
Let’s now create the schema file required by MongoDB. It tells you about the way fields are stored in MongoDB. Create a dbMessages.js file inside the messaging-app-backend folder.
You can now use the schema to create the endpoint that adds data to the database.
In server.js, create a POST request to the /messages/new endpoint. The load is in req.body to MongoDB. Then use create() to send dbMessage. If it’s a success, you receive status 201; otherwise, you receive status 500.
Next, create the GET endpoint to /messages/sync to get the data from the database. You are using find() here. You receive status 200 if successful (otherwise, status 500).
To check the routes, use the Postman app. Download it and install it.

Initial GET request
In Postman, you need to change the request to POST and then add the http://localhost:9000/messages/new endpoint.

POST request
Next, click the Send button. If everything is correct, you get Status: 201 Created, as seen in Figure 4-13.

GET request

Network error fix

Pusher dashboard

Create app in Pusher

Front end and back end

Back-end code
In the server.js file, import it and then use the Pusher initialization code. Get the initialization code from the Pusher website (https://pusher.com). To add the code, open a database connection with db.once. Then watch the message collection from MongoDB with watch().
To test this, you need to send a POST request from Postman. At the same time, you need to be in the Debug console in Pusher.

Message in Pusher

Server logs

Console log
Next, return to App.js and include the local axios first. Then use axios in the useEffect hook to get all the data from the /messages/sync endpoint. After receiving the messages, you set it through setMessages(). Finally, pass the messages as props to the chat component.
In the Chat.js file, use this message’s props and map through it to display on the screen.

New messages
Add the logic to POST directly from the message box. First, import the local axios and then create an input state variable.
Then do the value and onChange React thing on input and attach a sendMessage function to the onClick event handler of the button.

Message from input
Next, let’s add Google authentication to the project so that the user can log in with their Google account.

Additional settings

Web icon

Firebase hosting

The next screen

Global install

Continue

Config details
Open the code in Visual Studio Code and create a firebase.js file inside the src folder. Paste the content from VSCode.

Login screen

Get started

Google login

Enable Google login
Next, in the Login.js file, you need to import auth, provider from the local Firebase file. After that, use the signInWithPopup() method to get the results. The updated content is marked in bold.

Google authentication success
Let’s dispatch the user data into the data layer, and here the Redux/Context API comes into play.
When you get the user data back from Google, you dispatch it to the reducer in the Login.js file, and it is stored in the data layer.

Logged in
You have access to the user’s data, so you can use it anywhere. Let’s use the user’s Google image as the avatar in the Sidebar.js file. Let’s remove the extra rooms because this project has only one room where everyone can chat.

Login image
In Chat.js, use the useStateValue hook to get the user’s display name. Then check whether message.name is equal to user.displayName to display the chat__receiver class. Fix the hard-coded Last seen at... message in the chat__header in the Chat.js file; update so that it shows the time that the last person messaged. Also change the room name to Dev Help.

Time updates
The last thing to change is the hard-coded message in the sidebar. You need to show the last message here. First, send the messages from the App.js file to the sidebar component.
Finally, in the SidebarChat.js file, show the last message instead of the hard-coded message, and change the room name to Dev Help.

App complete
Go to www.heroku.com to deploy the back end. Follow the same procedure that you did in Chapter 1 and create an app named messaging-app-backend.

Initial route check
In this chapter, you created a simple but functional chat app. Firebase hosted it on the Internet. You learned to add Google authentication, by which you can log in with a Google account. You also learned to store the chats in a MongoDB database with API routes created using Node.js.
In this chapter, you are going to build an awesome photo-based social network using the MERN framework. The back end is hosted in Heroku, and the front-end site is hosted using Firebase. The authentication functionality is also handled by Firebase.
Material-UI provides the icons in the project. Pusher is used since MongoDB is not a real-time database like Firebase. You want the posts to reflect the moment someone hits the Submit button.

Final app
Since the front-end site is hosted through Firebase, you can create the basic setting while create-react-app creates the React app. Following the setup instructions from Chapter 1, I created photo-social-mern in the Firebase console.

Config

Perfect logo
Let’s now create the post component, which contains the logged-in user’s avatar, including a photo and a brief description. Create a components folder inside the src folder. Then, create two files—Post.js and Post.css—inside the components folder.

Styled post
Next, let’s optimize the code in App.js. Here, you use the useState hook to create new state posts. The posts here are objects inside an array.

Everything dynamic
Let’s work on the Firebase authentication, which allows you to log in to the app and post. This project uses email-based authentication, which is different from the Google authentication in the previous chapter.

Get started

Email and password

Enable email and password
Now, let’s show a sign-up modal from Material-UI . The code for this is from https://material-ui.com/components/modal/#modal.
First, import several dependencies and two styles in the App.js file. After that you have the constant of classes and modalStyle. The open state is initially set to false.
Inside return, set the open state to true for the modal and sign-up button .

Modal popup
Before creating the form, you need to create three state variables—username, email, and password—in the App.js file.
Fields for the username, email, and password are inside the modal in the App.js file. There is also a button that includes an onClick handler calling a signUp function.

Sign-up form
Let’s add authentication to the app. First, import auth from the local Firebase, and then add a new user state variable in the App.js file.
Add code to the signUp function that uses createUserWithEmailAndPassword from Firebase and passes the email and password. After that, update the user and set the displayName as the username. Use the useEffect hook to monitor any user changes, and use setUser() to update the user variable.
Inside the return, check if the user is logged in and then show either the Log out button or the Sign up button.

User sign-up
Now let’s work on the sign-in functionality by creating a new sign-in button and a new modal component in the App.js file.
First, create the openSignIn state variable and function in the App.js file. The function contains signInWithEmailAndPassword from Firebase.

Sign-in popup
The Firebase user authentication is complete. Add the code for the posts and upload the images. You return to this part once you start the back end.
Create new files—ImageUpload.js and ImageUpload.css—inside the components folder and import them into the App.js file. Next, pass the prop username from ImageUpload in the App.js file.
In the ImageUpload.js file, start with the basic content. There is an input box for the caption and another for the image. There is also a button and a progress bar.

Image upload

Initial back end
The MongoDB setup is the same as described in Chapter 1. Follow those instructions and create a new project named photo-social-mern.
Create a server.js file in the photo-social-backend folder. Here, you import the Express and Mongoose packages. Then use Express to create a port variable to run on port 9000.
The first API endpoint is a simple GET request created by app.get(), which shows the text Hello TheWebDev if successful.

Initial route
In MongoDB, you need to create a database user and give network access. The process is the same as explained in Chapter 1. Follow those instructions, and then get the user credentials and connection URL.
In the server.js file, create a connection_url variable and paste the URL within the string from MongoDB. You need to provide the password that you saved earlier and a database name.
Let’s create the model for the post. Create a postModel.js file inside the photo-social-backend folder .
You now use the schema to create the endpoint that adds data to the database.
In server.js, create a POST request to the /upload endpoint. The load is in req.body to MongoDB. Then use create() to send dbPost. If it’s a success, you receive status 201; otherwise, you receive status 500.
Next, create the GET endpoint to /sync to get the data from the database. You are using find() here. You receive status 200 if successful (otherwise, status 500).
In Postman, you need to change the request to POST and then add the http://localhost:9000/upload endpoint.

Postman POST
Next, click the Send button. If everything is correct, you get Status: 201 Created, as seen in Figure 5-18.

Postman GET
Sometimes you get an error in the server while POST requests. The error is UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connection.

Add current IP
In the ImageUpload.js file, import storage from Firebase and Axios. Update handleUpload(), which fires after you click the Upload button.
First, take the uploaded image path in the uploadTask variable and put it in the database. Check state_changed because the snapshot changes. Depending on how much hass uploaded, update the progress bar in setProgress.
After that, you need to do error management. Get the image URL from Firebase.
Next, take the caption, username, and URL and do an axios.post to /upload to push it in MongoDB.

Firebase storage

Cloud storage

MongoDB save
In App.js, you need to fetch the posts from MongoDB. First, import the local axios. Then create a new useEffect hook and make the GET request to the /sync endpoint.
Next, update App.js with the data you received from MongoDB.

Post from MongoDB
Since MongoDB is not a real-time database, it’s time to add a pusher to the app to get real-time data. Since you already did the setup in Chapter 4, follow the same instructions, and create an app named photo-social-mern.
In the server.js file, import it and then use the Pusher initialization code. Get the initialization code from the Pusher website (https://pusher.com). To add the code, open a database connection with db.once. Then watch the message collection from MongoDB with watch().
To test this, you need to upload a new image from the front end. At the same time, you need to be in the Debug console in Pusher.

Pusher log
Go to Postman and send another POST request. You see the data from the console log on localhost. The app is complete. Whenever you post something, it is shown in real time.
Go to www.heroku.com to deploy the back end. Follow the same procedure that you did Chapter 1 and create an app named photo-social-backend.

Environment variables in Heroku

Back end deployed
In this chapter, you created a simple but functional photo-based social network. Firebase hosted it on the Internet. You learned to add email authentication, by which you can log in with email. You also learned how to store images in Firebase and store links to images and posts in a MongoDB database with API routes created using Node.js.
Welcome to the final MERN project, where you build an awesome popular social network using the MERN framework. The back end is hosted in Heroku, and the front-end site is hosted in Firebase. Firebase also handles the authentication functionality. Material-UI provides the icons in this project. You also use styled components and CSS.
Pusher is used since MongoDB is not a real-time database like Firebase, and you want the posts to reflect the moment someone hits the submit.

Final app
Since the front-end site is hosted through Firebase, you can create the basic setting while create-react-app creates the React app. Following the setup instructions from Chapter 1, I created popular-social-mern in the Firebase console.
Since you also are using authentication functionality, you need to do the additional configuration mentioned in Chapter 4 and get firebaseConfig, which you need to copy.
Let’s create a component that displays a nice header in the app. To do this, create a components folder inside the src folder, and then create a Header.js file inside the components folder.
A lot of code is placed in Header.js, but it is mainly static code and uses Material UI icons. Note that styled components are used in all the files.

Beautiful header

Nice sidebar
Complete the front of the web app by adding a widget from the page plugin in Facebook. Add this in the right sidebar so that the app looks complete. Connect using a Facebook developer account (https://developers.facebook.com/docs/plugins/page-plugin/), so you can use it in any web app.

Adding widget

Getting iFrame

Widget shown
Next, let’s complete the Feed.js file by implementing the component through which the user can write a description for the post and upload an image. Two more components are added here. Create a new Messenger.js file in the components folder.
Let’s create the Messenger.js file. Here, you mainly have the MessengerTop and MessengerBottom components. In MessengerTop, you mainly have a text box, a file, and a button. You make the button invisible with display: none in its CSS. Most of the functionality is in it once you set the back end.

Messenger component
Next, let’s show posts in the web app. The Post component is in the Feed.js file. It is hard-coded now but comes from the back end soon.
Create a new Post.js file inside the components folder. Here, the PostTop section shows the avatar, username, and time. PostBottom shows the message and an image.

Posts shown
Let’s work on the Google authentication, which allows you to log in to the app and post. Here, you use the process from Chapter 4 and add it to the Firebase console.

Login screen

Login details
Let’s dispatch the user data into the data layer, and here the Redux/Context API comes into play.
In the Login.js file , when you get user data back from Google, you dispatch it to the reducer, and it is stored in the data layer.

Logged in

Login details

Initial back-end setup
The MongoDB setup is the same as explained in Chapter 1. Follow those instructions and create a new project named popular-social-mern.
Create a server.js file in the photo-social-backend folder. Here, you import the Express and Mongoose packages. Then use Express to create a port variable to run on port 9000.
The first API endpoint is a simple GET request created by app.get(), which shows the text Hello TheWebDev if successful.

Route test
In MongoDB, you need to create a database user and give network access. The process is the same as explained in Chapter 1. Follow those instructions, and then get the user credentials and connection URL.
In the server.js file, create a connection_url variable and paste the URL within the string from MongoDB. You need to provide the password that you saved earlier and a database name.
You are using GridFS to store the images. You installed it earlier through the multer-gridfs-storage package. The gridfs-stream package is responsible for reading and rendering to the user’s stream.
Complete the code to upload the image. First, create a gfs variable, and then use the conn variable to connect to the database. Next, use Grid to connect to the database and then create a collection of images to store the pics.
Next, create the storage variable, which calls a GridFsStorage function with an object. Here, the connection_url variable is used. Inside a promise, create a unique filename by appending the current date to it. Create a fileInfo object containing the filename and the bucketName as the earlier create collection images.
Use the multer package to upload the image by passing the variable created earlier.
Check the endpoint in Postman. Open a POST request to http://localhost:9000/upload/image.

POST request

Post image

Image chunk
Create the route to get the file. To do this, create a /images/single GET route, which takes a parameter filename. Then use the findOne method to find the file.
Next, let’s test the GET route to receive an image in Postman.

GET request
Until now, the process was to get the image and save it in MongoDB. Now that you have the image details, you can save it in MongoDB with other post details.
To do this, you need to create the route to save the post. First, create the model for the post. Then create a postModel.js file inside the popular-social-backend folder.
You now use the schema to create the endpoint that adds data to the database.
In server.js, create a POST request to the /upload endpoint. The load is in req.body to MongoDB. Then use create() to send dbPost. If it’s a success, you receive status 201; otherwise, you receive status 500.
Next, create the GET endpoint to /sync to get the data from the database. You are using find() here. You receive status 200 if successful (otherwise, status 500). A timestamp sorts the posts.
Do the necessary imports in the Feed.js file. After that, you have a postsData state variable. Next, call a syncFeed function from useEffect once.
In Messenger.js, add the imports for axios and FormData, which append the new image.
Update handleSubmit(). Here, check for the image that you already uploaded—and then append the image and the image name in the form.
Use axios.post to send the image to the /upload/image endpoint. In the then part, create a postData object to take the text from the user-entered input. imgName contains the name of the image from res.data.filename. The user and avatar are taken from the Firebase data and the timestamp is from Date.now().
Call the savePost() with the postData object. Note that there is an else, where you are not sending the image to savePost(). This is for cases where the user creates a post without any image.

Problem
Since MongoDB is not a real-time database, it’s time to add a pusher to the app for real-time data. Since you already did the setup in Chapter 4, follow the same instructions, and create an app named photo-social-mern.
And now back in the app, you can post anything in real time.
Go to www.heroku.com to deploy the back end. Follow the same procedure that you did Chapter 1 and create an app named popular-social-backend.

Back end deployed
It’s time to deploy the front end in Firebase. Follow the same procedure that you did in Chapter 1.
After this process, the site is live and working properly.
In this chapter, you created a simple but functional social network. Firebase hosted it on the Internet. You learned to add Google authentication, by which you can log in with the Google account. You also learned how to store images in MongoDB and to give real-time capabilities to MongoDB using Pusher.