DEV Community

Samuel Idowu
Samuel Idowu

Posted on

From Zero to Hero: A Beginner's Guide to Building Web Apps with the MERN Stack

Are you eager to dive into the world of full-stack web development but don't know where to start? Look no further! This comprehensive MERN stack tutorial for beginners will guide you through the process of building web apps with the MERN stack, taking you from a novice to a confident developer.

Introduction

The MERN stack is a powerful combination of technologies used to build modern web applications. It consists of MongoDB, Express.js, React, and Node.js. By the end of this guide, you'll understand how these components work together and be ready to create your own dynamic web applications.

What is the MERN Stack?

Before we dive into the details, let's break down the MERN stack components:

MongoDB: A flexible, scalable NoSQL database
Express.js: A backend web application framework for Node.js
React: A popular frontend JavaScript library for building user interfaces
Node.js: A JavaScript runtime environment that executes code outside a web browser

Together, these technologies enable you to build full-stack JavaScript applications, making the development process more streamlined and efficient.

Setting Up Your Development Environment

To start building web apps with the MERN stack, you'll need to set up your development environment:

  1. Install Node.js: Download and install Node.js from the official website.
  2. Install MongoDB: Follow the installation guide for your operating system on the MongoDB website.
  3. Choose a code editor: We recommend Visual Studio Code for its excellent JavaScript support.

Building Your First MERN Stack Application

Let's create a simple todo list application to demonstrate how the MERN stack works together.

Step 1: Setting Up the Backend

First, we'll create the server-side of our application using Node.js and Express.js.

  1. Create a new project directory and initialize a Node.js project:

mkdir mern-todo-app
cd mern-todo-app
npm init -y

  1. Install the necessary dependencies:

npm install express mongoose cors

  1. Create a server.js file and set up a basic Express server:

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

const app = express();
const PORT = process.env.PORT || 5000;

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

mongoose.connect('mongodb://localhost/mern-todo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

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

Step 2: Creating the MongoDB Schema

Now, let's define the schema for our todo items:

  1. Create a models folder and add a Todo.js file:

const mongoose = require('mongoose');

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

module.exports = mongoose.model('Todo', TodoSchema);

Step 3: Implementing API Routes

Next, we'll create the API routes for our todo application:

  1. Create a routes folder and add a todos.js file:

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

// Get all todos
router.get('/', async (req, res) => {
try {
const todos = await Todo.find();
res.json(todos);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Create a new todo
router.post('/', async (req, res) => {
const todo = new Todo({
text: req.body.text,
});

try {
const newTodo = await todo.save();
res.status(201).json(newTodo);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Add more routes for updating and deleting todos

module.exports = router;

  1. Update server.js to use the new routes:

const todosRouter = require('./routes/todos');
app.use('/api/todos', todosRouter);

Step 4: Setting Up the Frontend with React

Now that our backend is ready, let's create the frontend using React:

  1. In the project root directory, create a new React app:

npx create-react-app client
cd client

  1. Install additional dependencies:

npm install axios

  1. Replace the contents of src/App.js with the following code:

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

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

useEffect(() => {
fetchTodos();
}, []);

const fetchTodos = async () => {
const response = await axios.get('http://localhost:5000/api/todos');
setTodos(response.data);
};

const addTodo = async (e) => {
e.preventDefault();
await axios.post('http://localhost:5000/api/todos', { text: newTodo });
setNewTodo('');
fetchTodos();
};

return (


MERN Stack Todo App



type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Enter a new todo"
/>
Add Todo

    {todos.map((todo) => (
  • {todo.text}
  • ))}


);
}

export default App;

Running Your MERN Stack Application

To run your application, follow these steps:

  1. Start the backend server:
    node server.js

  2. In a separate terminal, start the React development server:

cd client
npm start

Your MERN stack todo application should now be up and running!

Conclusion

Congratulations! You've just built your first web app with the MERN stack. This tutorial has given you a solid foundation in full-stack JavaScript development. As you continue to explore and build with the MERN stack, you'll discover its flexibility and power in creating modern web applications.

Remember, practice makes perfect. Keep experimenting with different features and functionalities to enhance your skills. Happy coding!

Next Steps

To further improve your MERN stack skills, consider the following:

  1. Implement user authentication using JSON Web Tokens (JWT)
  2. Add more complex CRUD operations to your todo app
  3. Explore advanced React concepts like Redux for state management
  4. Learn about deployment strategies for MERN stack applications

By continuing to build and learn, you'll soon become a MERN stack expert!

Top comments (0)