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.

Step 1: Setting Up the Project Environment

1.1 Install Node.js and npm

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

1.2 Initialize the Project

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

Step 2: Setting Up the Backend

2.1 Install Backend Dependencies

You’ll need Express.js for creating the server, Mongoose for interacting with MongoDB, and other useful packages:
npm install express mongoose cors dotenv

2.2 Create the Server

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}`));

2.3 Create API Routes

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);

Step 3: Setting Up the Frontend

3.1 Create the React Application

Use Create React App to bootstrap your frontend project:

npx create-react-app client
cd client

3.2 Install Frontend Dependencies

You’ll need Axios for making HTTP requests:

npm install axios react-router-dom

3.3 Set Up Routing

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;

In src/App.js, set up routing:

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;

Step 4: Connecting Frontend and Backend

4.1 Create API Service

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`);
};

4.2 Fetch Data in React Components

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;

Step 5: Deploying the Application

5.1 Prepare for Deployment

Build your React app:
cd client
npm run build

5.2 Serve the React App with Express

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’));
});

5.3 Deploy to a Platform

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

How Can TechDotBit Help You Learn About MERN Stack Development?

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!

Conclusion

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!

[contact-form-7 id="0f5d249" title="Quote Form"]