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.
Join the DZone community and get the full member experience.
Join For FreeIntroduction 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
- MongoDB: A NoSQL database that stores data in JSON-like documents. It is highly scalable and allows for flexible and dynamic data schemas.
- 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.
- React: React lets you build user interfaces out of individual pieces called components. Create your own React components like
Thumbnail
,LikeButton
, andVideo
. Then combine them into entire screens, pages, and apps. - 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:
mkdir mern-example
cd mern-example
Initialize a new Node.js project:
npm init -y
Step 2: Installing Dependencies
Install the server's required dependencies:
npm install express mongoose dotenv cors body-parser
Install the React client's dependencies:
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:
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:
MONGO_URI=your_mongodb_connection_string
Step 4: Setting up the Client
Locate and launch the React development server from the client directory:
cd client
npm start
Open the client/src/App.js
file and replace its content with the following code:
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.
Opinions expressed by DZone contributors are their own.
Comments