Knowledge Base Hub

Browse through our helpful how-to guides to get the fastest solutions to your technical issues.

Home  >  VPS FAQ  >  How To Get Started with the MERN Stack?

How To Get Started with the MERN Stack?

 4 min

MERN refers to a set of four technologies: MongoDB, Express, React, and Node.js. Together, they keep the entire application in a single language, covering both frontend and backend. This guide walks through building a simple task manager so you can see how each component connects to the next.

How Do You Set Up the MERN Stack?

Node.js runs your backend code, and npm comes bundled with it to manage packages. Install the latest LTS version from the official Node.js website, then confirm both are set up correctly:

Step 1: Install Node.js and npm

bash
node -v
npm -v

Step 2: Create Your Project Folder

Start with a root folder, then split it into two subfolders, one for the backend and one for the frontend. Keeping them separate from the beginning saves confusion later.

bash
mkdir mern-todo-app
cd mern-todo-app
mkdir backend frontend

Step 3: Initialise the Backend

Move into the backend folder and run npm init to create a package.json file. From there, install Express along with a few supporting packages you’ll need.

bash
cd backend
npm init -y
npm install express mongoose cors dotenv

Create a server.js file. This is where Express actually starts listening for requests:

javascript
const express = require('express');
const cors = require('cors');
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}`));

Step 4: Connect to MongoDB

Sign up for a free MongoDB Atlas cluster, then place your connection string inside a .env file so it remains closer to your codebase.

MONGO_URI=your_mongodb_connection_string
PORT=5000

Connect Mongoose to your database inside server.js so it links up on startup:

javascript
const mongoose = require('mongoose');

mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log('MongoDB connected'))
  .catch((err) => console.error(err));

Step 5: Build Your API Routes

Inside a models folder, add a Todo.js file that defines what a single todo item looks like:

javascript
const mongoose = require('mongoose');

const TodoSchema = new mongoose.Schema({
  task: { type: String, required: true },
  completed: { type: Boolean, default: false }
});

module.exports = mongoose.model('Todo', TodoSchema);
Add routes in server.js to create and fetch todos:
javascript
const Todo = require('./models/Todo');

app.get('/api/todos', async (req, res) => {
  const todos = await Todo.find();
  res.json(todos);
});

app.post('/api/todos', async (req, res) => {
  const newTodo = new Todo({ task: req.body.task });
  const savedTodo = await newTodo.save();
  res.json(savedTodo);
});

Test each route with a tool such as Postman before connecting it to your frontend.

Step 6: Set Up the React Frontend

Move into your frontend folder and build a new React project:

bash
cd ../frontend
npx create-react-app .
npm start

This confirms React runs correctly on its own development server, usually at localhost:3000.

Step 7: Connect Frontend and Backend

Install Axios in your frontend folder, then call your Express API from a React component:

bash
npm install axios
javascript
import axios from 'axios';
import { useEffect, useState } from 'react';

function App() {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:5000/api/todos')
      .then((res) => setTodos(res.data));
  }, []);

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo._id}>{todo.task}</li>
      ))}
    </ul>
  );
}

export default App;

Step 8: Run the Full Application

Start both servers in separate terminal windows:

bash
# Terminal 1
cd backend && node server.js

# Terminal 2
cd frontend && npm start

Your React app now fetches data from Express, which reads from and writes to MongoDB.

A Few Important Considerations

  • Environment variables: The connection string and other sensitive values need a place outside your actual code, and .env is that place. Check it’s excluded from version control before pushing anything.
  • Folder structure: Routes, models, and controllers each deserve their own file from the start. Going back to split them apart once the backend has grown into a single large file is a much bigger job than doing it early.
  • Error handling: A failed database call without a try-catch block around it doesn’t fail quietly. It can crash the server outright or return information that was never meant to reach the user.
  • CORS configuration: Leaving all origins open is harmless while testing locally, but that same setting in production opens the door wider than it should be. Restrict it to your actual frontend domain before release.
  • Deployment: Once the app runs cleanly on your machine, the backend and frontend don’t have to be deployed at the same time. Deploy them as separate services, or bundle them into one, based on whatever the hosting setup calls for.
  • Version control: Git should start with your very first commit, not get added after the project takes shape. Early tracking makes debugging and collaboration noticeably easier as the project grows.

The MERN stack takes some repetition to feel natural, but the pattern holds steady from one project to the next: Node and Express handle the server, MongoDB stores the data, and React renders what the user actually sees. 

For our Knowledge Base visitors only
Get 10% OFF on Hosting
Special Offer!
30
MINS
59
SECS
Claim the discount before it’s too late. Use the coupon code:
STORYSAVER
Note: Copy the coupon code and apply it on checkout.