
How to Build a Basic Web Application with MERN Stack
How to Build a Basic Web Application with MERN Stack
How to Build a Basic Web Application with MERN Stack - Building a web application can seem daunting, especially if you are a beginner. However, with the right tools and guidance, it is possible to create a basic web application using the MERN stack. The MERN stack stands for MongoDB, Express.js, React, and Node.js. In this article, we will walk you through the steps to build a basic web application using the MERN stack.
Table of Contents
- Introduction
- What is the MERN stack?
- Setting up the development environment
- Creating the backend with Node.js and Express.js
- Connecting the backend to MongoDB
- Creating the frontend with React
- Connecting the frontend to the backend
- Testing the application
- Deploying the application
- Conclusion
- FAQs
1. Introduction
Web development is an essential part of today's world, and there are many web application frameworks available for building web applications. One such framework is the MERN stack. The MERN stack is a full-stack JavaScript solution that is used to build web applications. It consists of MongoDB, Express.js, React, and Node.js. In this article, we will learn how to build a basic web application using the MERN stack.
2. What is the MERN stack?
The MERN stack is a full-stack JavaScript solution that is used to build web applications. It consists of the following components:
- MongoDB: a NoSQL database that stores data in JSON-like documents.
- Express.js: a backend web application framework that provides a set of features for building web applications.
- React: a frontend library that allows building dynamic user interfaces.
- Node.js: a runtime environment that allows running JavaScript code outside of a web browser.
The MERN stack is popular because it allows developers to build scalable and efficient web applications using a single programming language, JavaScript.
3. Setting up the development environment
Before we begin building the web application, we need to set up the development environment. We will need to install the following software:
- Node.js and npm (Node Package Manager)
- MongoDB
- Visual Studio Code (optional)
4. Creating the backend with Node.js and Express.js
The backend is responsible for handling requests from the frontend and returning responses. To create the backend, we will use Node.js and Express.js.
First, we need to create a new Node.js project. Open the terminal and run the following command:
mkdir backend
cd backend
npm init -y
This will create a new Node.js project and initialize a package.json file.
Next, we need to install Express.js. Run the following command:
npm install express
This will install Express.js and add it as a dependency in the package.json file.
Now, create a new file named index.js in the root directory of the project. This file will contain the backend code. Here is an example code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
This code creates a new Express.js app, defines a route that returns a "Hello World!" message when the root URL is requested, and starts the server on port 3000.
To start the server, run the following command:
node index.js
Now, if you open your web browser and go to http://localhost:3000, you should see the "Hello World!" message.
5. Connecting the backend to MongoDB
Now that we have created the backend, we need to connect it to MongoDB. MongoDB is a NoSQL database that stores data in JSON-like documents. We will use the official MongoDB Node.js driver to connect to the database.
First, we need to install the MongoDB Node.js driver. Run the following command:
npm install mongodb
This will install the MongoDB Node.js driver and add it as a dependency in the package.json file.
Next, we need to create a new file named db.js in the root directory of the project. This file will contain the database connection code. Here is an example code:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myapp';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) {
console.log(err);
return;
}
console.log('Connected to MongoDB');
const db = client.db();
// Add database operations here
client.close();
});
This code creates a new MongoClient instance and connects to the MongoDB server running on localhost:27017 with the myapp database. We then log a message to the console if the connection is successful.
To add database operations, we can use the db instance. Here is an example of inserting a document into a collection:
const collection = db.collection('users');
const user = { name: 'John', email: 'john@example.com' };
collection.insertOne(user, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log('User inserted:', result.insertedId);
});
This code inserts a new user document into the users collection and logs the inserted document's ID to the console.
6. Creating the frontend with React
The frontend is responsible for rendering the user interface and interacting with the backend through API calls. To create the frontend, we will use React.
First, we need to create a new React project. Open the terminal and run the following command:
npx create-react-app frontend
cd frontend
This will create a new React project in the frontend directory.
Next, we need to install the following dependencies:
- axios: a library for making API requests
- react-router-dom: a library for handling client-side routing in React
- bootstrap: a CSS framework for styling the application
Run the following command to install these dependencies:
npm install axios react-router-dom bootstrap
Now, we can start building the frontend.
7. Connecting the frontend to the backend
To connect the frontend to the backend, we need to make API requests to the backend endpoints. We will use axios to make these requests.
First, we need to define the backend endpoint URLs. In this example, we will define a single endpoint that returns a list of users. Create a new file named api.js in the src directory of the frontend project. Here is an example code:
import axios from 'axios';
const baseUrl = 'http://localhost:3000';
export const getUsers = async () => {
const response = await axios.get(`${baseUrl}/users`);
return response.data;
};
This code exports a getUsers function that makes a GET request to the /users endpoint and returns the response data.
Next, we need to create a new React component that displays the list of users. Create a new file named Users.js in the src directory of the frontend project. Here is an example code:
import React, { useState, useEffect } from 'react
import React, { useState, useEffect } from 'react'; import { getUsers } from './api';
const Users = () => { const [users, setUsers] = useState([]);
useEffect(() => { const fetchUsers = async () => { const users = await getUsers(); setUsers(users); };
fetchUsers();
}, []);
return ( <div> <h1>Users</h1> <ul> {users.map((user) => ( <li key={user._id}> {user.name} ({user.email}) </li> ))} </ul> </div> ); };
export default Users;
This code defines a Users component that fetches the list of users using the getUsers function and displays them in an unordered list. We use the useState and useEffect hooks to manage the state of the users array and fetch the data when the component mounts.
Now, we can use this component in the App.js file to render the list of users. Replace the contents of the App.js file with the following code:
```javascript
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Users from './Users';
const App = () => {
return (
<Router>
<div className="container">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">MERN Stack</Link>
<div className="collapse navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link to="/" className="nav-link">Home</Link>
</li>
<li className="nav-item">
<Link to="/users" className="nav-link">Users</Link>
</li>
</ul>
</div>
</nav>
<Switch>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<h1>Welcome to MERN Stack</h1>
</Route>
</Switch>
</div>
</Router>
);
};
export default App;
This code defines the App component that renders a navigation bar with links to the Home and Users pages. We use the BrowserRouter, Switch, Route, and Link components from react-router-dom to handle client-side routing. The Users component is rendered when the /users path is matched, and the Home component is rendered for all other paths.
8. Styling the application with Bootstrap
To style the application, we will use Bootstrap. Bootstrap provides a set of CSS classes that we can use to style the UI components.
First, we need to import the Bootstrap CSS file in the index.js file. Add the following line at the top of the file:
import 'bootstrap/dist/css/bootstrap.min.css';
Next, we can apply the Bootstrap classes to the UI components. Here is an example code for styling the navigation bar:
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">MERN Stack</Link>
<div className="collapse navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link to="/" className="nav-link">Home</Link>
</li>
<li className="nav-item">
<Link to="/users" className="nav-link">Users</Link>
</li>
</ul>
</div>
</nav>
This code applies the navbar, navbar-expand-lg, navbar-light, and
bg-light classes to the navigation bar, which gives it a light background color and makes it expand to the full width of the screen on large screens.
We can also apply Bootstrap classes to the Users component to style the unordered list. Here is an example code:
import React, { useState, useEffect } from 'react';
import { getUsers } from './api';
const Users = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
const users = await getUsers();
setUsers(users);
};
fetchUsers();
}, []);
return (
<div>
<h1>Users</h1>
<ul className="list-group">
{users.map((user) => (
<li key={user._id} className="list-group-item">
{user.name} ({user.email})
</li>
))}
</ul>
</div>
);
};
export default Users;
This code applies the list-group and list-group-item classes to the unordered list and list items, respectively. This gives the list a border and padding.
9. Conclusion
In this article, we have learned how to build a basic web application with the MERN stack. We started by setting up the development environment and creating a new React project. Then, we created a simple API using Node.js and Express, and connected it to a MongoDB database using Mongoose. We also created a React component that fetches data from the API and displays it in the UI. Finally, we added client-side routing using React Router and styled the application using Bootstrap.
The MERN stack is a powerful and flexible stack for building full-stack web applications. It provides a wide range of tools and technologies that make it easy to develop, test, and deploy web applications. With the knowledge and skills you have gained from this article, you can now start building your own web applications using the MERN stack.
10. FAQs
- What is the MERN stack?
- The MERN stack is a combination of four technologies: MongoDB, Express.js, React, and Node.js. It is used to build full-stack web applications.
- What is React?
- React is a JavaScript library for building user interfaces. It allows developers to create reusable UI components and manage the state of the application.
- What is MongoDB?
- MongoDB is a NoSQL database that uses a document-based data model. It is used to store and retrieve data in web applications.
- What is Express.js?
- Express.js is a web application framework for Node.js. It provides a set of tools and utilities for building web applications.
- What is Node.js?
- Node.js is a JavaScript runtime environment that allows developers to run JavaScript code on the server-side. It is used to build scalable and high-performance web applications.
How to Build a Basic Web Application with MERN Stack
Tags: mern stack,mern stack tutorial,build a mern stack application,blog application using mern stack,full stack mern application,full stack,mern stack project,build and deploy a full stack mern application with crud,build and deploy a mern stack application,how to build a rest api with node js & express,login authenticator with mern stack,mern application,build a chat app with javascript,chat application with reactjs,mern stack tutorial for beginners
Author : parvezkhanats
For over the past decade, Parvez has developed a range of websites, web apps, custom CMS and CRM systems using PHP, MySQL, WordPress, Laravel, jQuery, HTML5, CSS3, XML, and Ajax for both startups and small businesses. His core expertise is in complete end-to-end management of new web development projects. Parvez joined WordPress to seek out opportunities to help clients build websites.Related Posts

Web Development Companies in Maheshwar
Web Development Companies in Maheshwar – Maheshwar, a vibrant city in India, is home toRead More

Web Development Companies in Mandu
Web Development Companies in Mandu – In today’s digital age, having a strong online presenceRead More

Web Development Companies in Omkareshwar
Web Development Companies in Omkareshwar – Web development has become an integral part of establishingRead More