It can sometime be overwhelming to build a full-stack web application using a stack like MERN.

Setting up the the back end and connecting it with a client-side library like React to fetch and display data is just the beginning. One you have the data user will interact with, you need to focus on developing a functional User Interface (UI) for your web application. For some developers, UI can be the tricky part.

MERN is full-stack because it consists of MongDB, Express, React and Nodejs. Each of these technologies can be replaced with something comparable but it is common practice to use them together.

React is the library you will use to build the front-end of the web application. Express is a Nodejs framework that helps you to build a server that communicates to and fro with a NoSQL database like MongoDB.

In this tutorial, I am going to show you how to build a small web application using this technology stack, step-by-step. Along with building a simple web app, you will learn how to use the Material UI library to make the application look good. You can then use what you learn here for to make your own applications look better and be more functional.

Pre-requisites

Before we get started, install all the tools we are going to need to set up our application.

Nodejs

MongoDB

yarn

create-react-app

The last in the above list are installed using npm.

Set up the MERN App

To get started, you need to follow the steps below by opening your terminal and typing these commands. To keep you from getting lost, I will leave a comment before each command using # .

After this step, make sure your root project looks like below with some extra files and folders.

We are going to bootstrap the server using Babel. To setup and learn what Babel is, please read here.

The next step is to define the configuration you will need to proceed with server creation. Inside server , create a new file config/index.js and define the following inside it.

For MongoDB, I am going to use a local instance. If you want to use a cloud service (free tier), please read the steps to set it up and consume in a Node server app here.

Make sure add the dev script inside package.json .

Connect Database and the Server

Inside config directory, create a new file called dbConnection.js . Let us start by defining the MongoDB connection.

I am going to use Mongoose as ODM (Object Document Mapper). This helps write queries inside the Node server and create business logic behind it. It also provides a schema-based solution to create data models and define them in our Node app.

Although MongoDB is a schema-less database, Mongoose helps our application understand the data structure and organize it at the same time. The most basic benefit is to make a connection between the Express app when it bootstraps and the MongoDB instance on our local machine.

Let’s create a small server in the index.js file of the root of our web app. Here it is in action.

If you are getting a message like below (ignore the mongoose warning), this means our server is up and running and successfully connected to the local instance of the database.

Building The User Model

To demonstrate, I am going to create a user data model with properties to save the user data when a new user registers with our application. We are going to save user credentials and validate it using Mongoose in this section. Create a new file inside server/models/user.js .

We will start by importing the necessary dependencies at the top of our file and then create a new Mongoose Schema, userSchema which is an object with properties. Typically, NoSQL databases are super flexible, in that they allow us to put whatever we want in them without enforcing any specific kind of structure. However, Mongoose adds a layer of structure on top of the typical MongoDB way of doing things. This helps us perform additional validation to ensure that our users are not submitting any random data to our database without us having to write tons of boilerplate code ourselves.

We now use the userSchema object to add a virtual password field. Note that whatever property is described inside the userSchema object is going to be saved in the MongoDB document. We are not saving the password directly. We are creating a virtual field first to generate an encrypted hash of the password and then save it in our database.

A virtual field is a document property that can be used to combine different fields or decompose a single value into multiple values for storage but never gets carried on inside the MongoDB database itself.

Using the Nodejs crypto module we are creating a hash that updates the virtual password . The ‘salt’ field is a randomly generated string for each password. This terminology comes from cryptography. We are also putting in the logic of validating the password field and checking whether it is 6 characters long. Lastly, we export the User model to be used with routes and controllers logic in our server.

User Routes

Now, let’s write the business logic behind the routes to create for the React end to interact with the server. Create a new file server/controllers/user.js and write the following code. Import the user model first that from the previous section.

I have also added a helper function inside a separate file at the location server/helpers/dbErrorHandler.js to gracefully handle any error that occurs in any of the routes like we are using in above and respond back with a meaningful message. You can download the file from here.

In the file above, we are creating three controller functions. The first one, registerUser , creates a new user in the database from the JSON object received in a POST request from the client. The JSON object is received inside req.body that contains the user credentials we need to store in the database. Further, user.save , saves the new user in the database. Notice that we are not creating a unique field which is common in this type of scenarios to identify each new user saved in our database. This is because MongoDB database creates an _id field each time a new record is saved.

The next function we are exporting is findUserById . It queries the database to find the specific details related to the user whose _id is provided in parametric route (which I will define shortly). If a matching user is found with that _id in the database, then the user object is returned and appended inside the req.profile .

findUserProfile controller function retrieves the user detail from req.profile and removes any sensitive information such as password's hash and salt values before sending this user object to the client. The last function deleteUser removes the the user details from the database.

Now let use the controller logic and add it to corresponding routes inside server/routes/user.js .

The controller functions are first imported and then used with their corresponding route.

Auth Routes

To restrict access to user operations — such as the logged in user can only access their profile and no one else’s — we are going to implement a JWT authentication to protect the routes. The two routes required to sign in and sign out the user from our application are going to be inside a separate file server/routes/auth.js .

The first route uses an HTTP POST request to authenticate a user with email and password credentials. The second route is used when the user hits the signout button (which we will implement in our front-end). The logic behind how these two routes work has to be defined in another file. Create a new file server/controllers/auth.js with the following code.

I am using two JWT related packages from npm to enable authentication and protect our routes: express-jwt and jsonwebtoken . You already installed them when we bootstrapped this project. The first controller function signin we are exporting receives user's credentials in req.body . Email is used to retrieve the matching user from the database. Remember, we have added a unique field when defining the userSchema .

Since we are also receiving user’s password, we are going to verify it with the hash and the salt value that we stored in our database. The signed JWT is returned to the client to authenticate the user with their details if successful. We are using browser’s cookies here to store the JWT token. You can use the browser’s local storage for this purpose.

The signout function above clears the cookie containing the signed JWT token. The last two functions are important for our application. Both requireSignin and hasAuthorization are used to protect access to certain routes from an unauthorized user. They check and validate the user on client whether they are authenticated to give access.

requireSignin method here verifies a valid JWT in the Authorization header of the request. hasAuthorization allows a user to operate protected routes by checking that the user who is sending the request is identical to the authenticated user. In our application we are going to use this on one protected route. We are going to delete the user profile and their data from the database in that route.

Now let us use these methods to protect user routes. Open server/routes/user.js .

Finishing the back-end

With the routing logic set up, we can now complete the server by adding our routes to index.js file.

To test these routes, open up a REST Client like Postman or Insomnia and the URL http://localhost:4000/api/users with required fields in order to create a user.

If there are no errors, you are going to receive the message Successfully signed up! . This means the user has been added to the database. If you try to make a new user with same credentials, it will throw an error this time.

If you use a MongoDB Client to view the records of your local database like Mongo Compass or Robomongo, you can easily see newly created user’s details.

Using the same user credentials, we will attempt a sign-in. It should give us a JWT back.

It works!

Except for the sensitive information that we eliminated from the route, we are receiving back the token and a user object.

Now let’s find the user profile. Hit the URL http://localhost:4000/api/users/{USER_ID} where USER_ID is the same created by MongoDB database when adding the user record.

You have to add the Bearer before signed JWT returned from the previous request at the Header Authorization . This completes our API testing and now we can focus on building the front-end of our application.

Adding Material UI in React

There are a series of steps to follow to add the Material UI Library to our react app. Traverse in the client directory and follow the below steps. We are going to use Material Icons in SVG form, so let’s add that package.

Material-UI uses Roboto font and we have to add it through Google Font CDN to our client side. Open public/index.html add the following. Let’s also change the title.

To see if everything installed correctly and is working, run the client project using command yarn start . This will open the default React app that comes with create-react-app at URL http://localhost:3000 . To see our our assets (such as Roboto font) being loaded, go to Developer Tools and open Network tab. Refresh the page to reload the assets and you will notice that the font family is being loaded.

Defining the Home Page

Now let’s build the first component of our application. Create a new file inside src/components/Home.js and put the following content.

The first component we are importing from @material-ui in this file is withStyles . It allows us to style a component by declaring a styles object with access top-level styles such as we are using theme with our home component. We will define these top-level theme related styles shortly in App.js . Next, we are importing Card, CardContent, CardMedia to create a card view. CardMedia is used to display any media file whereas CardContent is used with Typography to output text. Typography is used to present hierarchy based styles over text to the content as clearly and efficiently as possible.

Now open up App.js and add the following content.

MuiThemeProvider and createMuiTheme classes are used to create default theme. The theme specifies the color of the components, darkness of the surfaces, level of shadow, appropriate opacity of ink elements, and so on. If you wish to customize the theme, you need to use the MuiThemeProvider component in order to inject a theme into your application. To configure a theme of your own, createMuiTheme is used. You can also make the theme dark by setting type to dark like we have done above. Lastly, <MuiThemeProvider theme={theme}> is where the top level styles are being passed to child components, in our case Home .

If you render the app by running yarn start , you will get the below output.

Adding React Router

We need a way to navigate different routes for the user to sign in and sign out. In this section, we will add react-router library to our app for this purpose.

react-router library is a collection of navigational components. To get started, create a new file inside src folder called Routes.js .

The Route component is the main building block of React Router. Anywhere that you want to only render content based on the location’s pathname, you should use a Route element. Switch is used to group different Route components. The route for the homepage, our Home component does include an exact prop. This is used to state that route should only match when the pathname matches the route’s path exactly. To use the newly created Routes, we have to make some changes to App.js to make it work.

The BrowserRouter defined above is used when you have a server that will handle dynamic requests.

Connecting Node server and React

I wrote an article for Crowdbotics dealing how to connect a Node.js server with the React front end here. We do not need to review the whole process. Just open your package.json and add the following for our app to kickstart.

Next, I am going to add methods to be used in different components that will handle API calls from our server side code. Create two new files inside utils directory: api-auth.js and api-user.js .

In api-auth.js , add the following.

The signin method takes care of user credentials from the view component (which we will create shortly), then uses fetch to make a POST call to verify the user credentials with the backend. The signout method uses fetch to make a GET call to the sign-out API endpoint on the back-end.

Front-End: Auth Components

Next, we will setup all the necessary components required for authentication.

One by one, I am going to create new files so please follow closely.

Create a new directory inside components and call it auth . Then, create a new file auth-helper.js .

These functions will help us manage the state of authentication in the browser. Using these methods our client side app will be able to check whether the user has logged in or not. To protect the routes, such as a user’s profile, from un-authorized access, we have to define a new component inside PrivateRoute.js and make use of the methods above.

We are going to use this component as an auth flow in the Routes.js we have defined. Components that rendered via this route component will only load when the user is authenticated. Our last component related to user authentication is to be defined inside Signin.js .

This is a form component that contains email and password field (_as we defined in state above) for the user to enter to get authenticated. redirectToReferrer property in state is what we are using if the user gets verified by the server or not. If the credentials entered by the user are valid, this property will trigger Redirect component of react-router-dom .

Front-End: User Components

Similarly to our auth routes, we are going to separate our user components inside components/user/ folder. First, we need a React component to register a new user. Create a file called Signup.js .

We start the component by declaring an empty state that contains various properties such as name, email, password and error. The open property is used to capture the state of a Dialog box.

In Material UI, a Dialog is a type of modal window that appears in front of app content to provide critical information or ask for a decision. The modal in our case will either render an error message or the confirmation message depending on the status returned from the server.

We are also defining two handler functions. handleChange changes the new value of every input field entered. clickSubmit invokes when a user after entering their credentials, submit the registration form. This function calls registerUser from the API to send the data to the backend for further actions.

Create a new file called Profile.js .

This component shows a single user who is authenticated by the back-end of our application. The profile information of each user is stored in the database. This is done by the init function we have defined above the render function of our component.

We are using redirectToSignin redirect to the user on sign-out. We are also adding a delete profile button as a separate component which has to be defined in a separate file called DeleteUser.js .

This component is used for deleting the user profile that exists in the database. It uses the same deleteUser API endpoint we defined in our back-end. deleteAccount method is responsible for handling this task.

Front-End: Completing the Navbar

In this section we are going to complete our client side routes by leveraging a Navbar component. Create a new file component/Navbar.js .

This Navbar component will allow us to access routes as views on the front-end. From react-router we are importing a High Order Component called withRouter to get access to history object's properties and consume our front-end routes dynamically.

Using Link from react-router and auth.isAuthenticated() from our authentication flow, we are checking for whether the user has access to authenticated routes or not, that is, if they are logged in to our application or not.

isActive highlights the view to which the current route is activated by the navigation component.

Running the Application

The next step is to import this navigation component inside Routes.js and define other necessary routes we need in our app. Open Routes.js and add the following.

After completing this test, let’s test our application. Make sure you are running the backend server using nr dev command in one tab in your terminal. Using another tab or window, traverse to client directory and run the command yarn start . Once the application starts, you will be welcomed by the Homepage, as below.

Notice in the navbar above there are three buttons. The home icon is for Home page highlighted red in color. If you move on to the sign in page, you will see the sign in button highlighted. We already have one user registered to our application (when we were building the API). Please enter the credentials (email: jane@doe.com and password: pass1234 or the credentials you entered) as shown below and submit the form.

On submitting the form you will be redirected to the home page as per the component logic. The changes can be noticed at the navigation menu. Instead of sign-up and sign-in, you will see My Profile and Sign Out button. Click My Profile and you can see the current user’s details.

On clicking the delete icon it will delete the user. You can also try signing out of the application by clicking on the sign out button from navigation and then you will be redirected to the home page.

Conclusion

We have reached the end. Even though this tutorial is lengthy and, a lot is going on, I am sure if you take your time, you will understand the concepts and the logic behind it. It is after all, a full-stack MERN application. It uses JSON Web Tokens as an authentication strategy.

If you want to learn how to deploy this application, you can continue to read this article.

You can find the complete source code for this tutorial below in a Github repository.👇

Building A Web Or Mobile App?

Crowdbotics is the fastest way to build, launch and scale an application.

Developer? Try out the Crowdbotics App Builder to quickly scaffold and deploy apps with a variety of popular frameworks.

Busy or non-technical? Join hundreds of happy teams building software with Crowdbotics PMs and expert developers. Scope timeline and cost with Crowdbotics Managed App Development for free.