The MERN stack—comprising MongoDB, Express.js, React, and Node.js—is a powerful combination for developing full-stack web applications. In this blog, we’ll guide you through the steps to build a MERN stack project from scratch, covering each component and how they work together to create a robust web application.
Before you start, ensure you have Node.js and npm (Node Package Manager) installed. They are crucial for managing your project dependencies and running your development server.
You can download Node.js from the official website, which includes npm. After installation, verify it by running:
node -v
npm -v
Create a new directory for your project and navigate into it:
mkdir my-mern-app
cd my-mern-app
Initialize a new Node.js project:
npm init -y
You’ll need Express.js for creating the server, Mongoose for interacting with MongoDB, and other useful packages:
npm install express mongoose cors dotenv
Create a file named server.js
in the root of your project:
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());
const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI;
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log(‘MongoDB connected’))
.catch(err => console.error(err));
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Set up your routes in a directory named routes
. For instance, create routes/api.js
:
const express = require(‘express’);
const router = express.Router();
// Example route
router.get(‘/test’, (req, res) => {
res.json({ message: ‘API is working’ });
});
module.exports = router;
In server.js, include the routes:
const apiRoutes = require(‘./routes/api’);
app.use(‘/api’, apiRoutes);
Use Create React App to bootstrap your frontend project:
npx create-react-app client
cd client
You’ll need Axios for making HTTP requests:
npm install axios react-router-dom
Create a src/routes directory and add files for your components. For example, Home.js:
import React from ‘react’;
const Home = () => {
return (
<div>
<h1>Welcome to the Home Page</h1>
</div>
);
};
export default Home;
import React from ‘react’;
import { BrowserRouter as Router, Route, Switch } from ‘react-router-dom’;
import Home from ‘./routes/Home’;
const App = () => {
return (
<Router>
<Switch>
<Route path=“/” exact component={Home} />
{/* Add more routes here */}
</Switch>
</Router>
);
};
export default App;
In the client/src directory, create an api folder and add a file api.js:
import axios from ‘axios’;
const API_URL = ‘http://localhost:5000/api’;
export const fetchTest = () => {
return axios.get(`${API_URL}/test`);
};
Update Home.js
to use the API service:
import React, { useEffect, useState } from ‘react’;
import { fetchTest } from ‘../api/api’;
const Home = () => {
const [message, setMessage] = useState(”);
useEffect(() => {
fetchTest().then(response => {
setMessage(response.data.message);
}).catch(err => console.error(err));
}, []);
return (
<div>
<h1>{message}</h1>
</div>
);
};
export default Home;
Build your React app:
cd client
npm run build
In server.js
, add:
const path = require(‘path’);
app.use(express.static(path.join(__dirname, ‘client/build’)));
app.get(‘*’, (req, res) => {
res.sendFile(path.join(__dirname, ‘client/build’, ‘index.html’));
});
You can deploy your app to platforms like Heroku, Vercel, or DigitalOcean. Each has its own deployment process. For Heroku, you might follow:
heroku create
git push heroku main
TechDotBit is your go-to resource for mastering MERN stack development. We offer in-depth tutorials on MongoDB, Express.js, React, and Node.js, alongside hands-on projects and interactive coding exercises to solidify your skills. Benefit from expert insights, best practices, and community support to enhance your learning experience. With structured learning paths, access to valuable resources, and career development tools, TechDotBit equips you to build robust web applications and advance your career in full-stack development. Choose confidently with TechDotBit—reach out today!
You’ve now set up a basic MERN stack application! This guide covers the essentials, but there’s plenty more you can explore, such as authentication, advanced state management with Redux, and more sophisticated routing. The MERN stack provides a flexible foundation for building modern, scalable web applications, so dive in and start building your next project!