EN ES
Home > Web development > Javascript Tutorials > How to Build a Full Application with MERN (MongoDB, Express, React, Node.js)

How to Build a Full Application with MERN (MongoDB, Express, React, Node.js)

Diego Cortés
Diego Cortés
September 19, 2024
How to Build a Full Application with MERN (MongoDB, Express, React, Node.js)

Building a complete web application may seem like a monumental task, but with the MERN stack (MongoDB, Express, React, and Node.js), this process is greatly simplified. This article will guide you through the necessary steps to create a valid and functional application, providing a brief description of each technology and an example of practical implementation.

What is the MERN Stack?

The MERN stack is a set of technologies used to develop full web applications, both on the client-side and the server-side. This stack includes:

  • MongoDB: A NoSQL database that stores data in a document format, facilitating scalability and flexibility.
  • Express: An application framework for Node.js that simplifies the development of applications and APIs by creating servers.
  • React: A JavaScript library for building user interfaces, allowing for the creation of reusable components.
  • Node.js: A JavaScript runtime environment on the server that allows you to run JavaScript code outside of the browser.

Advantages of the MERN Stack

  • Full-Stack Development: You can develop both the frontend and backend using JavaScript.
  • Reusable Components: React allows you to build applications with components, making them easier to maintain.
  • NoSQL with MongoDB: The flexibility of MongoDB allows you to adapt to changes in data models without complications.
  • Scalability: Using Node.js along with MongoDB makes it easier to create scalable applications.

Step 1: Setting Up the Environment

Prerequisites

Before you begin, make sure you have the following installed:

  1. Node.js and npm: You can download and install the latest version from nodejs.org.
  2. MongoDB: Set up MongoDB on your local machine or use a cloud service like MongoDB Atlas.

Create the Project

You can start a new project in a directory of your choice:

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

This command creates a package.json file that manages your project dependencies.

Step 2: Setting Up the Server with Express and Node.js

Install Dependencies

Install Express and other necessary dependencies:

npm install express mongoose cors dotenv
  • mongoose: To interact with MongoDB.
  • cors: To handle CORS headers.
  • dotenv: To manage environment variables.

Create a Basic Server

Now, create a new file in your project named server.js and add the following code:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

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

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

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.log(err));

// Start the server
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Configure the Database

Create a .env file and add your MongoDB connection URI:

MONGODB_URI=your_mongodb_uri_here

Step 3: Create a Data Model

Models in Mongoose are schemas that define the structure of your data. Create a folder called models and a file called Item.js:

const mongoose = require('mongoose');

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

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

Step 4: Create the Routes

To handle HTTP requests, you need to create the routes for your application. Create a folder called routes and a file called item.js:

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

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

// Create a new item
router.post('/', async (req, res) => {
    const item = new Item({
        name: req.body.name,
        price: req.body.price,
    });
    try {
        const savedItem = await item.save();
        res.status(201).json(savedItem);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

module.exports = router;

Then, import the routes in server.js:

const itemRoutes = require('./routes/item');

app.use('/api/items', itemRoutes);

Step 5: Setting Up the Frontend with React

Create the React Client

Use Create React App to initialize a new React application:

npx create-react-app client
cd client
npm start

Install Axios for HTTP Requests

In the client folder, install axios:

npm install axios

Create Components in React

Create a file named ItemList.js in the src folder:

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

const ItemList = () => {
    const [items, setItems] = useState([]);

    useEffect(() => {
        const fetchItems = async () => {
            const res = await axios.get('http://localhost:5000/api/items');
            setItems(res.data);
        };
        fetchItems();
    }, []);

    return (
        <div>
            <h1>Item List</h1>
            <ul>
                {items.map(item => (
                    <li key={item._id}>{item.name} - ${item.price}</li>
                ))}
            </ul>
        </div>
    );
};

export default ItemList;

Then, update App.js to use ItemList:

import React from 'react';
import ItemList from './ItemList';

const App = () => {
    return (
        <div>
            <ItemList />
        </div>
    );
};

export default App;

Step 6: Testing and Deployment

Test the Application

Start the server and the React application separately:

  1. Open a terminal and run node server.js in the server folder.
  2. Open another terminal and run npm start in the client folder.

Visit http://localhost:3000 in your browser, and you should see the list of items.

Deploying the Application

You can deploy your application using platforms like Heroku or Vercel. Set up your MongoDB Atlas database and all necessary settings to ensure that your application works correctly in production.

Conclusion

The MERN stack is a powerful tool for building complete and scalable web applications. In this article, you learned how to set up a basic application using MongoDB, Express, React, and Node.js. With this foundation, you can explore more functionalities and expand your application with new features. Take advantage of all the flexibility and power that this stack offers to develop innovative projects. Good luck!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 36.79 ms