DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Mastering MERN Full Stack Development
  • Monorepo Development With React, Node.js, and PostgreSQL With Prisma and ClickHouse
  • Building a Full-Stack Resume Screening Application With AI
  • Building a Tic-Tac-Toe Game Using React

Trending

  • Securing the AI Host: Spring AI MCP Server Communication With API Keys
  • DevOps and Platform Engineering Readiness Checklist: Everything Needed for a Scalable, Secure, High-Velocity Delivery Platform
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka
  1. DZone
  2. Coding
  3. JavaScript
  4. Mastering Full-Stack Development: A Comprehensive Beginner’s Guide to the MERN Stack

Mastering Full-Stack Development: A Comprehensive Beginner’s Guide to the MERN Stack

From setting up your environment to building dynamic web applications: a step-by-step journey through MongoDB, Express.js, React, and Node.js.

By 
Nitesh Upadhyaya user avatar
Nitesh Upadhyaya
DZone Core CORE ·
Jul. 17, 24 · Analysis
Likes (5)
Comment
Save
Tweet
Share
6.3K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction to MERN Stack Development

There are four technologies that, when bought together, are perfect for building robust enterprise web applications: MongoDB, Express.js, React, and Node.js. The combined tech stack is called the MERN stack. The choice of these stacks makes them very powerful for architecting a full-fledged system and provides great flexibility.

Components of the MERN Stack

  1. MongoDB: A NoSQL database that stores data in JSON-like documents. It is highly scalable and allows for flexible and dynamic data schemas.
  2. Express.js: Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  3. React: React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.
  4. Node.js: Node.js is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools, and scripts.

Setting up a MERN Stack Application

Make sure you have Node.js and npm (Node Package Manager) installed on your computer before starting to work with the sample code. They are available for download on the official Node.js website.

Step 1: Setting up the Project

Create a new directory for your MERN stack project and navigate into it:

Shell
 
mkdir mern-example
cd mern-example


Initialize a new Node.js project:

Shell
 
npm init -y


Step 2: Installing Dependencies

Install the server's required dependencies:

Shell
 
npm install express mongoose dotenv cors body-parser


Install the React client's dependencies:

Shell
 
npx create-react-app client


Step 3: Setting up the Server

In the root directory, create a new file called server.js and insert the following code:

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

const app = express();
const PORT = process.env.PORT || 5000;

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

mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
}).then(() => {
  console.log('Connected to MongoDB');
}).catch((error) => {
  console.error('Error connecting to MongoDB:', error);
});

const itemSchema = new mongoose.Schema({
  name: String,
});

const Item = mongoose.model('Item', itemSchema);

app.get('/api/items', async (req, res) => {
  const items = await Item.find();
  res.json(items);
});

app.post('/api/items', async (req, res) => {
  const newItem = new Item(req.body);
  await newItem.save();
  res.json(newItem);
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});


Create a .env file in the root directory and add your MongoDB connection string:

Plain Text
 
MONGO_URI=your_mongodb_connection_string


Step 4: Setting up the Client

Locate and launch the React development server from the client directory:

Shell
 
cd client
npm start


Open the client/src/App.js file and replace its content with the following code:

JavaScript
 
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [items, setItems] = useState([]);
  const [newItem, setNewItem] = useState('');

  useEffect(() => {
    async function fetchItems() {
      const response = await axios.get('http://localhost:5000/api/items');
      setItems(response.data);
    }
    fetchItems();
  }, []);

  const addItem = async () => {
    const response = await axios.post('http://localhost:5000/api/items', { name: newItem });
    setItems([...items, response.data]);
    setNewItem('');
  };

  return (
    <div>
      <h1>Items</h1>
      <ul>
        {items.map(item => (
          <li key={item._id}>{item.name}</li>
        ))}
      </ul>
      <input
        type="text"
        value={newItem}
        onChange={(e) => setNewItem(e.target.value)}
      />
      <button onClick={addItem}>Add Item</button>
    </div>
  );
}

export default App;


Conclusion

The above tutorial gives a quick overview of how different technologies can come together to build a robust and flexible web application. We use MongoDB as a NoSQL database for persistence, Express.js as a server, React for building SPAs with a modular architecture, and Node.js as a run-time environment. Such systems are very robust and powerful, and they provide plug-in and plug-out flexibility for future events when you decide to switch the technologies.

MongoDB Node.js React (JavaScript library) MERN (stack)

Opinions expressed by DZone contributors are their own.

Related

  • Mastering MERN Full Stack Development
  • Monorepo Development With React, Node.js, and PostgreSQL With Prisma and ClickHouse
  • Building a Full-Stack Resume Screening Application With AI
  • Building a Tic-Tac-Toe Game Using React

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook