Creating a Full Stack Application with MERN: Guide for Beginners Tutorial

The MERN stack (MongoDB, Express, React, and Node.js) is a popular choice for developing full-stack web applications. It uses JavaScript across the entire development stack, making it easier to switch between the front end and back end without having to learn another language.

In this tutorial, we’ll walk through the steps of building a full-stack MERN application, explaining each component and how they fit together.


Step 1: Introduction to the MERN Stack

Before we dive into the setup and code, let’s take a quick look at each component of the MERN stack:

  • MongoDB: A NoSQL database where you store data in a flexible, JSON-like format.
  • Express.js: A web framework for Node.js that helps you handle HTTP requests and responses.
  • React: A front-end library for building user interfaces, especially single-page applications (SPAs).
  • Node.js: A JavaScript runtime that allows you to run JavaScript code outside of the browser, commonly used for backend development.

Together, these technologies allow you to build a full-stack application where the front end and back end communicate seamlessly.


Step 2: Setting Up Your Development Environment

2.1 Install Node.js and NPM

To get started, you need to install Node.js and npm (Node Package Manager) on your machine. You can download and install the latest version of Node.js from the official Node.js website.

Check your installation by running the following commands in the terminal:

bash
node -v
npm -v

2.2 Install MongoDB

Next, you’ll need MongoDB to handle the database for your application. You can download and install MongoDB from the official MongoDB website. Alternatively, you can use MongoDB Atlas, a cloud-based MongoDB solution.


Step 3: Create the Backend with Node.js and Express

3.1 Initialize a New Node.js Project

Open your terminal and create a new folder for your project. Then, navigate to that folder and initialize a new Node.js project:

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

This will create a package.json file that will keep track of your project’s dependencies.

3.2 Install Express and Other Dependencies

Install the required packages for your back-end development:

bash
npm install express mongoose cors
  • Express: Web framework to handle routes and middleware.
  • Mongoose: A MongoDB object data modeling (ODM) library.
  • CORS: Middleware that allows cross-origin resource sharing, which is needed to communicate between the front-end and back-end servers.

3.3 Create the Server with Express

Now, let’s create the basic Express server. In your project folder, create a new file named server.js and add the following code:

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

const app = express();
const PORT = 5000;

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

// Simple route
app.get('/', (req, res) => {
res.send('Hello from the backend!');
});

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

3.4 Connect to MongoDB with Mongoose

Next, set up the connection to MongoDB using Mongoose. You need to connect your Express app to a MongoDB database.

Add this code to server.js to connect to MongoDB:

javascript
const dbURI = 'mongodb://localhost:27017/mernapp';

mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));

Make sure you have MongoDB running on your local machine (or use MongoDB Atlas for a cloud solution).

3.5 Create a Basic Model

Create a basic Mongoose model. In a new folder called models, create a file named Item.js:

javascript
const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});

module.exports = mongoose.model('Item', ItemSchema);

Now you can use this model to interact with your MongoDB database.


Step 4: Build the Front End with React

4.1 Install React

Create a new React app inside the client folder:

bash
npx create-react-app client
cd client
npm start

This will create a new React project and start the development server.

4.2 Build the UI

In your src folder, delete the default files inside src except for App.js and index.js. Modify App.js to display a basic UI. For now, we’ll just create a form to add items and a list to display the items.

Here’s a simple form and list:

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

function App() {
const [items, setItems] = useState([]);
const [name, setName] = useState('');

const fetchItems = async () => {
const res = await fetch('http://localhost:5000/api/items');
const data = await res.json();
setItems(data);
};

const addItem = async () => {
const res = await fetch('http://localhost:5000/api/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name })
});
const data = await res.json();
setItems([...items, data]);
setName('');
};

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

return (
<div>
<h1>Item List</h1>
<form onSubmit={(e) => {
e.preventDefault();
addItem();
}}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Add item"
/>
<button type="submit">Add</button>
</form>
<ul>
{items.map(item => (
<li key={item._id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default App;

Step 5: Connect Front End and Back End

Now you need to connect the React front end to the Express back end.

5.1 Set Up API Routes in Express

In server.js, add the following API routes for fetching and adding items:

javascript
const Item = require('./models/Item');

// Route to get items
app.get('/api/items', async (req, res) => {
const items = await Item.find();
res.json(items);
});

// Route to add an item
app.post('/api/items', async (req, res) => {
const newItem = new Item({ name: req.body.name });
const item = await newItem.save();
res.json(item);
});

5.2 Proxy the React Requests

In your React project (client folder), open the package.json file and add the following proxy field:

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

This will proxy any API requests from React to your Express server running on port 5000.


Step 6: Testing Your MERN Application

Now that you have both the front-end and back-end set up, run both servers:

  1. Start your MongoDB instance.
  2. Run the back-end server:
bash
node server.js
  1. In another terminal, run the React front-end:
bash
cd client
npm start

Now open your browser and navigate to http://localhost:3000. You should be able to add and display items through your MERN application.

Post Comment