Skip to main content

Command Palette

Search for a command to run...

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

Published
4 min read
Step-by-Step Guide to Creating a MERN Stack App
A

As a passionate Full Stack Developer, I specialize in building dynamic, scalable, and user-friendly web applications using the MERN stack. My journey has taken me through various technologies, including React, Node.js, Express, MongoDB, and more, where I've applied my skills in both front-end and back-end development to create efficient and robust software solutions.

In this blog, I'll walk you through creating a full-stack application using the MERN stack (MongoDB, Express, React, Node.js). By the end, you'll have a solid understanding of how to set up and build a full-stack project, ready to scale for real-world applications.

Let's dive in step by step, with no prior experience required!

1. What is the MERN Stack?

The MERN stack consists of:

  • MongoDB – NoSQL database used to store application data in a flexible, JSON-like format.

  • Express.js – Backend web framework that makes handling routes and server logic easy.

  • React – Frontend JavaScript library for building interactive UIs.

  • Node.js – JavaScript runtime that allows you to run JavaScript code outside the browser (on the server).

2. Prerequisites

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

  • Node.js – Download and install from nodejs.org.

  • MongoDB – You can use MongoDB Atlas for cloud-hosted MongoDB, or install it locally.

  • Git – For version control.

  • A code editor like VS Code.

3. Setting Up the Project

Let's start by creating the folder structure and initializing our Node.js project.

3.1 Create a New Project

  1. Open your terminal and create a new folder for your project:
mkdir mern-app
cd mern-app
  1. Initialize a new Node.js project:
npm init -y

3.2 Install Dependencies

We'll need Express for the backend, and we’ll set up a simple REST API.

npm install express mongoose cors dotenv
  • Express for creating the server.

  • Mongoose for interacting with MongoDB.

  • CORS to handle cross-origin requests (important when connecting frontend and backend).

  • dotenv to manage environment variables.

4. Backend: Building the API with Node.js and Express

In the root folder, create a new folder called backend and inside it, create index.js for your server code.

4.1 Setting up the Server

// backend/index.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();

const app = express();
app.use(cors());
app.use(express.json());

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

4.2 Creating the Routes

Let’s create basic routes for our application. Inside the backend folder, create another folder called routes and add a simple route for a sample API.

// backend/routes/sampleRoute.js
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('Hello, this is your first API route!');
});

module.exports = router;

Now connect this route in index.js:

// backend/index.js (update)
const sampleRoute = require('./routes/sampleRoute');
app.use('/api/sample', sampleRoute);

5. Connecting to MongoDB

We’ll use MongoDB Atlas to avoid local setup issues. Go to MongoDB Atlas and create a free account. Follow the steps to create a cluster, and once done, grab the connection string.

Add the connection string to a .env file in the root of your project:

MONGO_URI=your_mongodb_connection_string

Now, let's connect to MongoDB in index.js:

// backend/index.js (add mongoose connection)
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

6. Frontend: Building the UI with React

Let’s set up the frontend using React.

6.1 Creating the React App

Run the following command to create a React app in a folder named frontend:

npx create-react-app frontend
cd frontend

Once created, open App.js and modify it to fetch data from our Express backend:

// frontend/src/App.js
import React, { useState, useEffect } from 'react';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    fetch('/api/sample')
      .then(response => response.text())
      .then(data => setMessage(data));
  }, []);

  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}

export default App;

6.2 Connecting React and Express

To make both the backend and frontend work together, we’ll use a proxy. Add this to your package.json in the frontend:

"proxy": "http://localhost:5000"

Now, run both the backend and frontend:

// In two separate terminals:
npm run start      // for the frontend
node backend/index.js   // for the backend

7. Integrating Backend with Frontend

In a real-world app, you would need to interact with databases, handle authentication, and implement advanced features. As a next step, you can create models in Mongoose and expose more routes via Express.

8. Deployment

Deploy the backend using services like Heroku and the frontend using Netlify or Vercel.

9. Conclusion

Congrats! 🎉 You've just built a full-stack app using the MERN stack. This is a solid foundation to start building more complex applications and explore topics like state management, authentication, and cloud deployments.

Keep building, and happy coding!