How to Build a Full-Stack App with MERN Stack

Introduction

If you want to develop a modern, scalable, and efficient web application, learning to build a full-stack app with the MERN Stack is the perfect starting point. The MERN Stack—comprising MongoDB, Express.js, React.js, and Node.js—allow developers to use JavaScript across the entire stack, streamlining the development process. In this guide, we will walk you through the steps to build a full-stack web application using the MERN Stack.


What is the MERN Stack?

The MERN Stack includes four powerful technologies that work together seamlessly:

  • MongoDB: A NoSQL database for storing data in JSON-like documents.
  • Express.js: A back-end framework for handling HTTP requests and creating APIs.
  • React.js: A front-end library for building dynamic user interfaces.
  • Node.js: A server-side JavaScript runtime environment.

These tools together enable you to build full-stack applications efficiently using JavaScript as a single programming language.


Step 1: Setting Up Your Development Environment

To begin, ensure you have the necessary tools installed:

  1. Install Node.js and npm: Download and install Node.js from nodejs.org.
  2. Install MongoDB: Download and install MongoDB Community Server from mongodb.com.
  3. Install a Code Editor: Use VSCode or any other preferred text editor.

Initialize Your Project

  • Create a project folder and initialize npm:
mkdir mern-app
 cd mern-app
 npm init -y

Step 2: Back-end development with Node.js and Express

Install Required Packages

Start by installing the essential dependencies:

npm install express mongoose dotenv cors

Set Up a Basic Server

Create a file server.js and write the following code:

const express = require("express");  
const mongoose = require("mongoose");  
const cors = require("cors");  
require("dotenv").config();  

const app = express();  
app.use(express.json());  
app.use(cors());  

// MongoDB Connection  
mongoose.connect(process.env.MONGO_URI, {  
  useNewUrlParser: true,  
  useUnifiedTopology: true,  
})  
.then(() => console.log("MongoDB Connected"))  
.catch((err) => console.error(err));  

// API Route  
app.get("/", (req, res) => {  
  res.send("Welcome to the MERN App Backend!");  
});  

// Start the server  
const PORT = process.env.PORT || 5000;  
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));  

Run Your Server

  • Add a MongoDB connection string to your .env file:
MONGO_URI=<Your MongoDB URI>
  • Start the server using:bashCopy codenode server.js

Your server should now be running on http://localhost:5000.


Step 3: Build the Front-End with React

Create React App

In the root folder, run the following command to set up a React app:

npx create-react-app client  
cd client  
npm start  

Connect React to the Backend

Install axios to make HTTP requests:

npm install axios

Update the App.js file in your React project to fetch data from the backend:

import React, { useEffect, useState } from "react";  
import axios from "axios";  

function App() {  
  const [message, setMessage] = useState("");  

  useEffect(() => {  
    axios.get("http://localhost:5000")  
      .then((response) => setMessage(response.data))  
      .catch((error) => console.error(error));  
  }, []);  

  return (  
    <div>  
      <h1>{message}</h1>  
    </div>  
  );  
}  

export default App;  

Now, when you run the React app, it will display the message from the backend server.


Step 4: Integrating MongoDB and Building a Full CRUD App

Create a MongoDB Model

In the server folder, create a models folder and a Task.js file:

const mongoose = require("mongoose");  

const TaskSchema = new mongoose.Schema({  
  title: { type: String, required: true },  
  description: String,  
  completed: { type: Boolean, default: false },  
});  

module.exports = mongoose.model("Task", TaskSchema);  

Set Up CRUD Routes

Create CRUD endpoints in server.js for tasks:

const Task = require("./models/Task");  

app.post("/api/tasks", async (req, res) => {  
  const task = new Task(req.body);  
  await task.save();  
  res.send(task);  
});  

app.get("/api/tasks", async (req, res) => {  
  const tasks = await Task.find();  
  res.send(tasks);  
});  

app.delete("/api/tasks/:id", async (req, res) => {  
  await Task.findByIdAndDelete(req.params.id);  
  res.send({ message: "Task deleted" });  
});  

Step 5: Connecting Front-End and Back-End

Create a simple UI in your React app to interact with the API using Axios:

  • Fetch and display tasks
  • Add new tasks
  • Delete tasks

Example for fetching tasks:

useEffect(() => {  
  axios.get("http://localhost:5000/api/tasks")  
    .then((response) => setTasks(response.data))  
    .catch((error) => console.error(error));  
}, []);  

Conclusion

By following this guide, you’ve learned how to build a full-stack app with the MERN Stack. The MERN Stack is a powerful, efficient, and modern tech stack that simplifies full-stack development by using JavaScript across all layers. Start small, build projects, and master these tools to unlock exciting opportunities as a full-stack developer.


Helpful Resources

Call to Action: Want to dive deeper? Start building your first MERN project today and elevate your web development skills!

m

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *