DEV Community

Cover image for Getting Started with the MERN Stack: A Beginner's Guide with Examples
Dimagi Sihilel
Dimagi Sihilel

Posted on

1 1

Getting Started with the MERN Stack: A Beginner's Guide with Examples

As a software engineering student, I’ve been diving into full-stack development, and the MERN stack — MongoDB, Express.js, React, and Node.js — keeps popping up. It’s a powerhouse for building modern web apps, covering both front-end and back-end with JavaScript. Curious about how it works? Let’s break it down, explore what each part does, and walk through a simple example to see MERN in action.

What’s the MERN Stack?

MERN is a full-stack framework that uses four technologies:

  • MongoDB: A NoSQL database that stores data as JSON-like
    documents. It’s flexible and scales well.

  • Express.js: A lightweight back-end framework running on Node.js. It handles routing and APIs.

  • React: A front-end library for building interactive UIs with
    components.

  • Node.js: A runtime that lets JavaScript run server-side, powering the back-end.

Together, they let you build everything from a to-do app to a social platform using one language — JavaScript. Pretty cool, right?

How It Fits Together

Imagine a blog app. MongoDB stores posts, Express.js and Node.js serve them via APIs, and React displays them in a slick UI. The flow is simple: React (front-end) talks to Express/Node (back-end) via HTTP requests, and Node fetches data from MongoDB. It’s a seamless loop, all in JS.

Let’s Build Something: A Mini To-Do App

To see MERN in action, let’s sketch out a basic to-do app. I’ll keep it simple — adding and listing tasks — with code snippets you can try.

1. Set Up the Back-End (Node.js + Express.js + MongoDB)

First, install Node.js and MongoDB (locally or use MongoDB Atlas for a free cloud DB). Create a project folder, run npm init -y, and install dependencies:

npm install express mongoose cors
Enter fullscreen mode Exit fullscreen mode

Here’s a basic server (server.js):

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();

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

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/todos', { useNewUrlParser: true });

const TodoSchema = new mongoose.Schema({ task: String });
const Todo = mongoose.model('Todo', TodoSchema);

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

// API to add a todo
app.post('/todos', async (req, res) => {
  const newTodo = new Todo({ task: req.body.task });
  await newTodo.save();
  res.json(newTodo);
});

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

This sets up a server with two endpoints: one to fetch todos and one to add them. MongoDB stores the tasks.

2. Build the Front-End (React)

Create a React app in a new folder:

npx create-react-app client
cd client
npm install axios
Enter fullscreen mode Exit fullscreen mode

Replace src/App.js with this:

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

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

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

  // Add a todo
  const addTodo = () => {
    axios.post('http://localhost:5000/todos', { task })
      .then(res => setTodos([...todos, res.data]));
    setTask('');
  };

  return (
    <div>
      <h1>To-Do List</h1>
      <input value={task} onChange={e => setTask(e.target.value)} />
      <button onClick={addTodo}>Add</button>
      <ul>
        {todos.map(todo => <li key={todo._id}>{todo.task}</li>)}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Start it with npm start — it runs on port 3000 by default.

3. Tie It Together

Run MongoDB (mongod in a terminal), then start the back-end (node server.js) and front-end (npm start). Open localhost:3000, type a task, hit "Add," and watch it appear. The back-end saves it to MongoDB, and React fetches the updated list.

Why MERN Rocks

  • One Language: JavaScript everywhere simplifies learning.

  • Fast Setup: Tools like create-react-app and Express get you coding quick.

  • Scalable: MongoDB and Node.js handle growth well.

Challenges

  • Learning Curve: Four techs can feel overwhelming at first.

  • CORS: You’ll need cors (like above) to connect front and back locally.

Pro Tips

  • Use nodemon (npm install -g nodemon) to auto-restart your server on changes.

  • Deploy it! Push the React build to Netlify and the back-end to Render or Heroku.

Wrapping Up

The MERN stack is like a Swiss Army knife for web dev — versatile and powerful. This to-do app is just a taste; you could add delete buttons, styling, or user logins next. As a student, I love how it lets me build real apps fast. Give it a shot — start small, tweak the code, and see where it takes you!

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)