Learn step-by-step how to build a full-stack application using the MERN stack—MongoDB, Express, React, and Node.js. Perfect for web devs seeking modern skills!
Table of content
The MERN stack is a popular set of technologies for building full-stack web applications using JavaScript. MERN stands for:
Combining these allows you to write both client and server code in JavaScript, streamlining development and deployment.
# Create a folder for your project
mkdir mern-app && cd mern-app
# Initialize Node.js project
npm init -y
# Install dependencies
npm install express mongoose cors dotenv
Create a file called server.js
:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
app.get('/', (req, res) => res.send('API Running!'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
.env
file.Organize your routes and controllers in separate files for scalability. For example, a simple users
route:
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => res.json([{ name: 'John Doe' }]));
module.exports = router;
Add the route to server.js
:
app.use('/api/users', require('./routes/users'));
# In project root (mern-app):
npx create-react-app client
cd client
npm start
Replace src/App.js
with:
import React, { useEffect, useState } from 'react';
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<div>
<h1>Users</h1>
<ul>
{users.map((user, idx) => <li key={idx}>{user.name}</li>)}
</ul>
</div>
);
}
export default App;
To allow the React app to communicate with the backend, set up a proxy
in client/package.json
:
"proxy": "http://localhost:5000",
This ensures API requests are properly routed during development.
node server.js
cd client && npm start
You’ve just built a simple full-stack application using the MERN stack! To go further, add authentication, deploy your app, and explore more advanced features. The MERN stack provides a solid foundation for scalable, modern web applications.