Setup MERN (MongoDB, Express JS, React JS, and Node JS) environment and create your first MERN stack application.
By: Manish Mandal
Tags: React, Mongodb, Expressjs, Reactjs, Nodejs

Setup MERN (MongoDB, Express JS, React JS, and Node JS) environment and create your first MERN stack application. Manish Mandal Follow Dec 10 · 8 min read

So are you also confused like most of the MERN beginners on how to create your first MERN project? and also how to setup the environment for your project? Even I was also confused when I created my first MERN project. I wanted to setup everything locally on my computer but there was hardly any tutorial for setting up the MongoDB locally everyone was using MongoDB atlas. But in this tutorial, I will cover how to use MongoDB locally and also how to structure our project.

We will first start with installing Node js on our machine. Visit node js official website here and download the latest version of node and install it on your machine. It’s available for your Linux, Mac, and Windows machine. I am using a Windows environment so all setup and configuration will be as per this environment. I have downloaded the Windows Installer (.msi) 64-bit version for my computer. After completion of download open the software and then it will ask for accepting the agreement and blah blah just click on next and after that, it will prompt you with this screen.

There is one checkbox to install Chocolatey on your machine. This is optional but still, I’ll recommend you to check this box as Chocolatey will help you to update your node in your machine easily in the future. After that click on install. After the installation has been completed you will be prompted with another screen to install python and visual studio build tools required for node native modules. Press any key to install all those required things.

We have successfully installed node in our machine now it’s time to install MongoDB in our machine. Visit MongoDB's official website to download the community version of MongoDB. The current version of MongoDB while writing this tutorial is 4.4.2. It can vary in the future but I guess the step would be the same. So I have downloaded MongoDB v4.4.2 Platform windows and Package MSI. After downloading follow the below animated steps to install MongoDB.

Note: I have also checked to install the MongoDB compass. MongoDB Compass will show your Database and its structure through an intuitive GUI.

After successfully installing MongoDB your MongoDB services will be running automatically in your windows services and the database data will be stored in Data Directory we have selected while installing the MongoDB software.

ctrl + shift + ESC open task manager and then go to the services tab

But by any chance, your MongoDB service is not listed you have to manually configure mongod for the command line and create a data directory for the database.

Optional if MongoDB service is not listed: If you type mongod to start your MongoDB connection you will be receiving an error like ‘mongod’ is not recognized as an internal or external command , this may be because our environment is not recognizing the command mongod . To fix this we need to add our MongoDB bin folder to the Environment variable. On your machine search for environment variable and open the Environment Variable dialog box and then edit the path variable and add your MongoDB installation bin folder to the box and click Ok.

Note: My current version is 4.4.2 that’s why the path contains a folder of 4.4. This may vary for your installation

Optional if MongoDB service is not listed: Now you will be able to run mongod command to start the database. But it will stop because there is one more thing we have to do is to create a data folder in our C drive. So go to your C drive and create a directory with the name data and inside that directory create another directory with the name db. This directory will hold all our database and its setting. Now you can run mongod command in your terminal to start MongoDB.

Note: The data directory we selected while installing MongoDB and the data directory we created in C drive manually hold different database so do not get confused that why your database is not listed or your collections are not showing. If mongodb services is running in your windows services do not run mongod command in terminal.

Now we can open MongoDB compass which we have installed simultaneously with MongoDB to create our Database and collections.

So we have successfully installed Node js and MongoDB on our Environment. Now it’s time to structure the boilerplate for the project.

Create and enter into the project directory and then inside that directory create a directory name backend and also one file name server.js. This server.js is the main file that you can use to call your database configuration and all your APIs routes. After that open terminal inside the root directory and run

npm init -y

This will create a package.json file in the project directory. Alternatively, you can use npm init for setting up the name or keywords for the project but that’s up to you.

Note: You can use require to import modules but I prefer using import to load node modules in files. To allow the node to use import add the below line to your package.json file

"type": "module"

2. Now we will install the required modules for our backend setup. Run the below command inside the terminal to install the required modules.

npm install express mongoose --save

3. After that we will config mongoose to connect with our MongoDB. Create a config directory inside the backend directory and then inside the config directory create a db.js file. This file will contain our database connection configurations. Paste the below code in the db.js file.

Note: Replace databasName with the name of your database.

4. Now import this db.js file to your server.js file and run node server.js in your terminal. It will log Database connected : 127.0.0.1

5. Now we will create a users collection in our database and its schema using mongoose. Create a models directory inside the backend directory and then inside the model create usersModel.js file and paste the below code.

6. Now just import the users model to the db.js file and it will create the users collection in your database with the schema. Open MongoDB compass to view the collection.

7. Now we will create some dummy users detail in our users collection. Open MongoDB compass and import below dummy data.

8. Now it’s time to create the controller which will be responsible for returning the response of the request. Create a controllers directory inside the backend directory and inside controllers create userController.js file.

9. Now in this file we will create two methods to retrieve all users and users by id but before that install, a module to act as a middleware for handling exceptions inside of async express routes.

npm i express-async-handler --save

10. Now paste the below code into the userController.js file.

11. Now we will create a route for the user. Create a routes directory inside backend directory and inside routes create userRoute.js file.

12. Paste the below code into the userRoute.js file.

13. Now it’s time to create our API but before that, I will install dotenv module to create a .env file in our project and then calling that into our server.js file. This .env file will help us in declaring our environment variable. We can save our credentials or keys here.

Install

npm i dotenv --save

Import

import dotenv from 'dotenv' dotenv.config()

14. Create a .env file in our project root directory and paste the below text to declare some variables.

15. Now will create user API using the express use method. We will also declare our PORT so now paste the below code into your server.js file.

16. Now run node server.js in your terminal to start the server on port 5000 and then open localhost:5000/api/users on your browser to get the list of all users.

We have successfully created our API using express js, node js, and MongoDB. Before moving into the React part I would like you to install the nodemon module and also make some changes to the package.json file.

npm i nodemon --save-dev

Now add this line under the scripts object inside the package.json file.

"start": "nodemon backend/server"

Now re-run your server using npm start in your terminal and this time, nodemon will monitor each change in your project and restart the server automatically.

Note: if you have used npm init -y to generate the package.json file please change "main": "index.js", to "main": "server.js" in your package.json file else nodemon will throw an error.

In most of my tutorials, I have covered how to use Axios to fetch data from the API to React. You can read my previous tutorial on the Simplest way to use axios to fetch data from an api in ReactJS. I won’t go much into detail like the above-mentioned tutorial but I will cover the basic part. So now go to the root directory of the project and follow the below-mentioned steps.

17. Create a react project with the name frontend.

npx create-react-app frontend



18. Install Axios into your react application.

npm install axios --save

19. Now replace all the code from the app.js file with the below-mentioned code.

Before starting our react application add the below line inside the package.json file of the react project or else you will receive a CORS error in your project.

"proxy": "http://127.0.0.1:5000",

20. Now start the application npm start and refresh the browser to see changes.

So now we have successfully built our first MERN project.

Tip: Instead of running node and react separately we can install a module to run them concurrently just install the concurrently module to your root project and add some lines mentioned below in your root package.json file.

npm i concurrently --save-dev

Now all you need is to run npm run dev from the terminal and both will start concurrently.

Below I have shared the GitHub repository for reference.