logo

How to Build a Full-Stack Web Application Using MERN

How to Build a Full-Stack Web Application Using MERN
By nitindhyani1234Created on: 10/13/2024

The MERN stack, comprising MongoDB, Express.js, React.js, and Node.js, is a powerful combination for building full-stack web applications. This JavaScript-based technology stack allows developers to create dynamic and responsive applications that provide seamless user experiences. In this blog post, we will guide you through the process of building a full-stack web application using the MERN stack, highlighting each component's role and offering practical steps to get you started.

  1. Understanding the MERN Stack

Before diving into development, it's essential to understand what each component of the MERN stack does:

  • MongoDB: A NoSQL database that stores data in flexible, JSON-like documents, making it easy to scale and handle diverse data types.
  • Express.js: A web application framework for Node.js that simplifies building server-side applications and APIs.
  • React.js: A front-end JavaScript library for building user interfaces, allowing for the creation of dynamic and interactive web applications.
  • Node.js: A JavaScript runtime that enables server-side scripting, allowing you to build scalable network applications.

  1. Prerequisites

Before you start building your full-stack web application, ensure you have the following:

  • Basic Knowledge of JavaScript: Familiarity with JavaScript is crucial as all four components of the MERN stack are JavaScript-based.
  • Development Environment: Set up your local development environment with Node.js and MongoDB installed. You can also use tools like Visual Studio Code for coding.

  1. Step-by-Step Guide to Building a MERN Application

Step 1: Setting Up the Project Structure

  1. Create the Project Folder: Start by creating a new folder for your project and navigate to it using the terminal.
1mkdir mern-app
2cd mern-app
  1. Initialize a Node.js Project: Run the following command to create a package.json file for your project.
1npm init -y
  1. Set Up the Backend: Create a folder for the server-side code.
1mkdir server
2cd server
  1. Install Required Packages: Install Express and Mongoose (for MongoDB interactions) using npm.
1npm install express mongoose dotenv cors
  1. Create the Server File: Create a file named server.js in the server folder and set up a basic Express server.
1const express = require('express');
2const mongoose = require('mongoose');
3const cors = require('cors');
4require('dotenv').config();
5
6const app = express();
7app.use(cors());
8app.use(express.json());
9
10const PORT = process.env.PORT || 5000;
11
12mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
13  .then(() => app.listen(PORT, () => console.log(,[object Object],)))
14  .catch(err => console.error(err));

Step 2: Building the Database Model

  1. Create a Model Folder: In the server folder, create a models folder.
1mkdir models
  1. Define a Mongoose Schema: Create a file named Item.js in the models folder to define your data structure.
1const mongoose = require('mongoose');
2
3const itemSchema = new mongoose.Schema({
4  name: { type: String, required: true },
5  quantity: { type: Number, required: true },
6});
7
8module.exports = mongoose.model('Item', itemSchema);

Step 3: Creating API Endpoints

  1. Set Up Routes: Create a folder named routes in the server folder and create a file named itemRoutes.js.
1mkdir routes
2touch routes/itemRoutes.js
  1. Define API Endpoints: Add CRUD operations for your items in itemRoutes.js.
1const express = require('express');
2const router = express.Router();
3const Item = require('../models/Item');
4
5// Create an item
6router.post('/', async (req, res) => {
7  const newItem = new Item(req.body);
8  try {
9    const savedItem = await newItem.save();
10    res.status(201).json(savedItem);
11  } catch (err) {
12    res.status(500).json(err);
13  }
14});
15
16// Get all items
17router.get('/', async (req, res) => {
18  try {
19    const items = await Item.find();
20    res.status(200).json(items);
21  } catch (err) {
22    res.status(500).json(err);
23  }
24});
25
26module.exports = router;
  1. Use the Routes: Update your server.js file to use the new routes.
1const itemRoutes = require('./routes/itemRoutes');
2app.use('/api/items', itemRoutes);

Step 4: Setting Up the Frontend with React

  1. Create the Client App: Navigate back to the root folder and create the React app using Create React App.
1cd ..
2npx create-react-app client
  1. Install Axios: Change to the client directory and install Axios for making HTTP requests.
1cd client
2npm install axios
  1. Set Up the Component: Create a component to fetch and display items. Create a new file named ItemList.js in the src folder.
1import React, { useEffect, useState } from 'react';
2import axios from 'axios';
3
4const ItemList = () => {
5  const [items, setItems] = useState([]);
6
7  useEffect(() => {
8    const fetchItems = async () => {
9      const response = await axios.get(',[object Object],');
10      setItems(response.data);
11    };
12    fetchItems();
13  }, []);
14
15  return (
16    <div>
17      <h1>Item List</h1>
18      <ul>
19        {items.map(item => (
20          <li key={item._id}>{item.name} - Quantity: {item.quantity}</li>
21        ))}
22      </ul>
23    </div>
24  );
25};
26
27export default ItemList;
  1. Render the Component: Modify App.js to render the ItemList component.
1import React from 'react';
2import ItemList from './ItemList';
3
4const App = () => {
5  return (
6    <div className="App">
7      <ItemList />
8    </div>
9  );
10};
11
12export default App;

Step 5: Connecting the Frontend and Backend

  1. Run the Server: Start your Express server.
1cd server
2node server.js
  1. Run the React App: Open a new terminal window, navigate to the client directory, and start the React app.
1cd client
2npm start
  1. Test Your Application: Open your browser and navigate to http://localhost:3000. You should see the item list fetched from your MongoDB database.

  1. Deploying Your MERN Application

Once you’ve built and tested your application, it’s time to deploy it. You can use platforms like Heroku or Vercel for easy deployment:

  1. Deploying the Backend: Push your server code to a GitHub repository and connect it to Heroku for deployment.
  2. Deploying the Frontend: Build your React app using npm run build and deploy it to a static hosting service like Vercel.

Conclusion

Building a full-stack web application using the MERN stack is a rewarding experience that enhances your development skills and opens up numerous possibilities for creating dynamic applications. By following this guide, you now have a foundational understanding of each component in the MERN stack and the steps required to build and deploy your own applications. As you grow more comfortable with MERN, you can explore advanced features like user authentication, state management with Redux, and real-time data with Socket.io.

No comments yet.