How to Build a Full-Stack Application with MERN

A Step-by-Step Guide to Creating a Scalable MERN Stack App

Madhu deepak
3 min read3 days ago
image by JavaScript Mastery

Introduction

The MERN stack (MongoDB, Express.js, React, and Node.js) is one of the most popular choices for full-stack development due to its efficiency, flexibility, and JavaScript-based architecture. Whether you’re a beginner or an experienced developer, building a full-stack application with MERN is a great way to enhance your skills. In this guide, we’ll walk you through the entire process of developing a scalable MERN application from scratch.

What is the MERN Stack?

The MERN stack consists of four main technologies:

  • MongoDB — A NoSQL database that stores data in a flexible, JSON-like format.
  • Express.js — A backend web framework for handling HTTP requests and API routes.
  • React.js — A front-end library for building dynamic user interfaces.
  • Node.js — A runtime environment that allows JavaScript to run on the server side.

Prerequisites

Before we start, make sure you have the following installed on your system:

  • Node.js and npm
  • MongoDB (locally or using a cloud service like MongoDB Atlas)
  • A code editor (e.g., VS Code)
  • Postman for testing APIs (optional but recommended)

Step 1: Setting Up the Backend with Node.js and Express

  1. Initialize a new Node.js project:
mkdir mern-app && cd mern-app
npm init -y

2. Install dependencies:

npm install express mongoose cors dotenv

3. Create an index.js file and set up an Express server:

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 })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));

app.listen(5000, () => console.log('Server running on port 5000'));

Step 2: Creating a MongoDB Database and Schema

  1. Define a model (models/User.js):
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
module.exports = mongoose.model('User', UserSchema);

2. Create API routes (routes/userRoutes.js):

const express = require('express');
const User = require('../models/User');
const router = express.Router();

router.post('/register', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (err) {
res.status(400).send(err);
}
});

module.exports = router;

3. Link routes to the main server file (index.js):

const userRoutes = require('./routes/userRoutes');
app.use('/api/users', userRoutes);

Step 3: Setting Up the Frontend with React

  1. Create a React app:
npx create-react-app client
cd client
npm start

2. Install Axios for API calls:

npm install axios react-router-dom

3. Create a simple form component (components/Register.js):

import React, { useState } from 'react';
import axios from 'axios';

function Register() {
const [formData, setFormData] = useState({ name: '', email: '', password: '' });

const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

const handleSubmit = async (e) => {
e.preventDefault();
await axios.post('http://localhost:5000/api/users/register', formData);
alert('User registered successfully!');
};

return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" placeholder="Name" onChange={handleChange} required />
<input type="email" name="email" placeholder="Email" onChange={handleChange} required />
<input type="password" name="password" placeholder="Password" onChange={handleChange} required />
<button type="submit">Register</button>
</form>
);
}

export default Register;

Step 4: Connecting the Frontend and Backend

  1. Modify package.json in the React app to proxy API requests:
"proxy": "http://localhost:5000"

2. Run both backend and frontend:

cd mern-app
npm start

3. Open another terminal and run:

cd mern-app
npm start

Conclusion

You’ve now built a basic full-stack MERN application! From setting up the backend with Node.js and Express to creating a frontend with React, this guide covered the essential steps to integrate the MERN stack. You can enhance this project by adding authentication, state management with Redux, or deploying it to platforms like Vercel and Heroku.

--

--

Madhu deepak
Madhu deepak

Written by Madhu deepak

Software Engineer and Developer

No responses yet