How to create a MERN stack app from scratch: A complete beginner’s guide

Dilshan Hiruna
10 min readJun 11, 2022

Have trouble getting started with your MERN project? No worries, I’ll guide you through a step-by-step on how to create a starter project using your favorite tech stack. You may probably know what MERN stands for which is for MongoDB, Express, ReactS, and NodeJS. Although you may know, let’s get started with having a clear idea about what are these technologies and what are they used for. Or if you don’t want it at all, you may skip to the implementation.

Introduction to MERN Stack

Now let’s talk about these technologies one by one.

NodeJs

If you have experience with Java or Python, you know that you can run the code on your computer itself. because of this, these languages can be used to code in back-end servers. But a language like javascript runs only in your browser environment which means you can’t use it to write server-side code. And…Not anymore. Node is a back-end javascript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. And yes!!! that means by using Node, now you have the power to write server-side code using javascript.

Express

Express is a web framework that runs on NodeJs that helps to build web/mobile applications. If you didn’t get what that means, Express is the framework that we used to create a server for our front-end applications using javascript. Express uses NodeJs to run the javascript code. By using Express, developers can make APIs really fast & easily.

MongoDB

MongoDB is the database provider of this tech stack. MongoDB is a NoSQL database and the most popular NoSQL database out there. This DB goes really handy with this tech stack and implementations are really simple and easy to learn as there are no query languages you don’t need to use. And in our implementations, we will use mongoose which is a JavaScript object-oriented programming library that creates a connection between MongoDB and the Express framework.

ReactJS

ReactJS is a javascript library (not a framework) developed and maintained by Meta (formally Facebook) that is used to build user interfaces based on components. Was initially released in 2013 and became the most popular javascript library among other front-end JS libraries and frameworks. React is used to build single-page web applications which means there is only a single HTML file that is being rendered. UIs are developed as components and mount or unmount through that single HTML file.

libraries vs framwork:

A library is similar to building a house from the ground up; you have the freedom to design your home however you want, with any architecture you want and the ability to organize your rooms however you want.
Framework, on the other hand, is similar to purchasing a new home; you won’t have to deal with any construction issues, but you won’t be able to choose how your rooms are organized because the house is already built.

Implementation

Installing NodeJS

Now you have an understanding of the technologies that we are going to use. Let’s get started by installing nodes into your local machine.

Step 1: Visit the Nodejs website

Step 2: Download the LTS (Long term support) version, which is recommended to most users

If you want to use multiple versions of node, NVM is the way

Step 3: Check whether node is successfully installed

NPM (Node Package Manager) installs with the Node installation. It is a command-line tool that installs, updates, or uninstalls Node.js packages in your application. Verify NPM installation as below.

NodeJs installation Done!!! 👏

Building the server (backend)

Creating an Express server

Now let's jump into building our server.

Create a folder and give a name whatever you want (eg: my-mern-project). And we are going to create two folders inside. One is for our backend and the other is for our frontend. Name these folders as server-client, api-client, or backend-frontend as it gives more sense.

And I am going to name it server and client.

Next move on to the server folder, because we are going to build the server first.

Before we begin, we need to initialize a node project.

Use the below command to initialize the project

npm init

And it will ask you for package name, versions, descriptions so and so. Don’t worry about it, keep them by default by pressing enter to all inputs.

Use npm init -y to initialize the project with the default values. Much easier way

Now let’s create our main server file.

Install express and cors dependencies

npm i express cors

Create a file called index.js and use the following code snippet

Now let’s check whether the server is running. But before that, you need to add the script to run the server file in the package.json file.

Add “start”: “node index.js” below the test script in your package.json file

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"cors": "^2.8.5",
"express": "^4.18.1"
}
}

Now use npm start or npm run start command to run the server

Now the server is running on port 5000.

Creating the backend folder structure

By now, our folder structure looks like this. Nothing much right?

Our next step is to create a proper folder structure so that we can manage and modify our server files easily in the future without making a mess out of it.

After creating folders, it will look like this.

common — where you keep files that are required in many places (eg: database configuration files, loggers)

controllers — where you keep your functions

middleware — where you keep middleware file

routes — where you define your API endpoints

models — where you define your MongoDB schemas

Configuring MongoDB connection

Step1: You should create a MongoDB instance. You can do this in two way

After creating a new database connection using one of those methods, you should probably get a URI similar to either one of those below. Save it!

mongodb+srv://server.example.com/
or
mongodb://localhost:27017

Step2: Initializing the database connection in our server

Install mongoose dependence (JS object-oriented programming library that creates a connection between MongoDB and the Express)

npm i mongoose

Create a new file named “db.js” or give whatever you want that makes sense in the common folder.

And replace “YOUR_MONGODB_URI” with the URI that you got after creating the DB connection.

And now we should import this file into our main server file (index.js)

Add the following line to index.js

const express = require("express");
const cors = require("cors");
const app = express();
require("./common/db")(); //database connection
app.use(cors({ origin: "*" }));
app.use(express.json());
const PORT = 5000;
app.listen(PORT, console.log(`Server running on port ${PORT}`));

Now let's run the server again.

Creating MongoDB Schemas

let's create a simple function to create users.

To save the user data in the database, we need to create the schema for that.

Go to the models folder and create a file named “users.js”

And we are going to use this schema in the controller files to perform the CRUD in the database.

Creating Controllers

This is the core of our server. This is where we define our function that is needed to be exposed by the server and used by the clients.

Now let's make simple API functions to create, view, update, and delete users

Go to the controllers folder and create a file named “users.js”

please make sure to install bcryptjs which is used to encrypt passwords

npm i bcryptjs

Creating routes

After creating the controllers, next, we need to expose these functions to the public. For that, we need to define URLs for every single function so that the client can access a specific function using the URL.

Go to the routes folder and create a file named “users.js”

Now, you need to import the user router into the main server file (index.js)

Run the server again to make sure that the server is running without any issue

Please use Postman or ThunderClient (VS code plugin) to check the APIs before implementing the frontend.

hooray… backend is done!!! 😎

Building the client (frontend)

Now we are good to go to the client’s side implementation.

As we are using React for the frontend, there are many ways to create a react app, but the best and easiest method is to use create-react-app, which is a command to create a react template. So let's go to the main project directory and run the below command

npx create-react-app client

The “client” in this cmd is the directory name, so the react project should create inside our client folder.

After the template creation, you should probably get as below.

Navigate to the client folder and run the below cmd

npm start

Now the react project must be running inside your browser. And you’ll have an already created UI. Don’t worry, it’s created by the template itself. We are going to remove it later and implement our own.

As we talked about earlier, React is a single-page application, which means that it has only one HTML page. If you go to the public folder you can see that HTML file.

And we are going to render all our components inside the div tag that has the id root (line 31, above image).

Navigate to the index.js file and you see how the div element is fetched by the id and the <App /> component is rendered inside that div tag with the id root. And whenever we define inside the App component, it will render inside the HTML page

Let’s create two components for SignUp and SignIn

Make a folder inside the src folder called “components”. And inside the components folder create two files named SignIn.js and SignUp.js

Please note that the component names should always start will a capital letter. This is to differentiate components from the basic HTML stage which is always in simple letters.

To make things easier, I have used SignUp and SignIn templates from MUI

Now recreate the App.js as below

Here, I have used a react hook to store the “signing”/“signup ” state. If the authType is “signin”, the SignIn component will render, but not the SignUp component. And if the authType is “signup”, the SignUp component will render, but not the SignIn. The benefit of this is that we can navigate between these two components without the need of refreshing the whole page.

If you have basic knowledge of useState react hooks, you know that we use the second value of the array to set the value which is setAuthType here. And we have sent it as a prop to both components so that we can use that and change the authType inside the SignIn or SignUp component.

And our next step is to call the API functions that we have created in the backend server

As the HTTP client, we use Axios

npm i axios

import Axios in the SignUp file and create a function to call the API

After adding the function, run the client again and test the signup function. Probably you’ll see a new entry in the MongoDB collection.

Now let's build the function for the signin

As for now, all the basic things are done in the frontend.

Please find the whole code from the below git repository

Conclusion

This blog teaches you how to create a starter project using the MERN stack. Starting from understanding the technologies one by one, we move on to the implementation from the server-side and the client-side.

--

--