Building full-stack applications with JavaScript has never been easier, thanks to the MERN Stack (MongoDB, Express.js, React.js, and Node.js). This powerful combination enables developers to build robust, scalable web applications entirely using JavaScript for both front-end and back-end development.
In this guide, we will walk you through the process of building a simple full-stack MERN app. By the end, you’ll have a working application with a React front-end that interacts with a Node.js back-end, using MongoDB for data storage. Let’s dive into the steps!
Before we start building, ensure that you have the following tools installed:
Create a new folder for your project and open the terminal.
Run the following command to initialize the project:
npm init -y
This will create a package.json
file where you can add dependencies.
For the back-end, you need to install Express.js, mongoose (for MongoDB integration), and cors (for cross-origin requests):
npm install express mongoose cors
index.js
file in your project’s root folder to set up the Express server.const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mernApp', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch((err) => console.log(err));
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This sets up the Express server and connects to MongoDB.
You will need API routes to handle CRUD operations. Let’s create a simple route to get and post data.
routes
and inside it, a file apiRoutes.js
:const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
// Define a simple model
const Item = mongoose.model('Item', new mongoose.Schema({
name: String,
}));
// Get all items
router.get('/items', async (req, res) => {
const items = await Item.find();
res.json(items);
});
// Add a new item
router.post('/items', async (req, res) => {
const newItem = new Item(req.body);
await newItem.save();
res.json(newItem);
});
module.exports = router;
client
folder (React app), we will create a simple UI to interact with the API.First, install Axios to make HTTP requests:
npm install axios
Create a simple component to display and add items:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState('');
useEffect(() => {
// Fetch items from the API
axios.get('http://localhost:5000/api/items')
.then(response => setItems(response.data));
}, []);
const handleAddItem = () => {
axios.post('http://localhost:5000/api/items', { name: newItem })
.then(response => {
setItems([...items, response.data]);
setNewItem('');
});
};
return (
<div>
<h1>MERN App</h1>
<ul>
{items.map(item => <li key={item._id}>{item.name}</li>)}
</ul>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Add new item"
/>
<button onClick={handleAddItem}>Add Item</button>
</div>
);
};
export default App;
This will allow you to view and add items to your app.
node index.js
cd client
npm start
Visit http://localhost:3000
to view the React front-end, where you can add and view items that are stored in MongoDB.
For deployment, you can deploy the back-end on platforms like Heroku and the front-end on Vercel or Netlify. Make sure to update the API URLs to match the deployed addresses.
Congratulations! You’ve now built a full-stack MERN app with a React front-end and a Node.js back-end, using MongoDB to store data. This app follows modern best practices for building scalable, efficient applications, and you can extend it with features like user authentication, real-time updates, and more.
By using the MERN stack, you can leverage JavaScript across the entire stack, making it easier to maintain and develop. As you grow more comfortable with the MERN stack, you can start building even more complex applications, adding more functionality, and exploring additional tools and techniques.