Building a Full-Stack MERN Application: MongoDB, Express, React, and Node.js
Building a full-stack application has never been easier with the MERN stack, which consists of MongoDB, Express, React, and Node.js. This powerful combination of technologies enables developers to create scalable and feature-rich applications with ease. In this blog post, we will dive into the process of building a MERN application from scratch, focusing on each technology's role and how they interact with one another. We will also provide you with clear, beginner-friendly explanations and code examples to help you understand and follow along.
What is the MERN Stack?
MERN is an acronym that stands for MongoDB, Express, React, and Node.js. Together, they form a complete technology stack that enables you to build both the frontend and backend of a web application. Let's break down each component:
- MongoDB: A NoSQL database that stores data in a flexible, JSON-like format called BSON. It is highly scalable and provides high performance.
- Express: A minimal and flexible web application framework for Node.js, designed to make building web applications and APIs easier.
- React: A popular JavaScript library for building user interfaces, created by Facebook. It enables developers to create reusable UI components that manage their own state.
- Node.js: An open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a browser.
Setting Up the Development Environment
Before we begin building our application, let's set up the development environment. Ensure that you have the following software installed on your machine:
- Node.js (v14 or higher): Download here
- MongoDB (v4 or higher): Download here
- A code editor like Visual Studio Code: Download here
Creating a New Project
Open your terminal or command prompt and navigate to the folder where you want to create your project. Run the following commands to create a new directory and navigate into it:
mkdir mern-app cd mern-app
Setting Up the Backend
Initializing the Project
First, let's initialize our project with a package.json
file. Run the following command and follow the prompts:
npm init -y
Installing Dependencies
Install the necessary dependencies for our backend by running the following command:
npm install express mongoose dotenv cors
Here's a brief overview of these packages:
express
: The Express.js framework for building our web application.mongoose
: A MongoDB object modeling tool that provides a schema-based solution for our database.dotenv
: A package that allows us to load environment variables from a.env
file.cors
: A package to enable Cross-Origin Resource Sharing (CORS) for our application.
Creating the Backend Structure
Create a new folder named backend
in the mern-app
directory. Inside the backend
folder, create the following files and folders:
backend/
│───controllers/
│───models/
│───routes/
├───.env
├───app.js
Now let's configure our application.
Configuring the Backend
Setting Up the .env File
Open the .env
file and add the following lines:
MONGODB_URI=mongodb://localhost:27017/mern-app
PORT=5000
Here, we're setting the MongoDB connection string and the port number our backend will run on.
Setting Up app.js
Open the app.js
file and add the following code:
const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); const dotenv = require('dotenv'); // Load environment variables dotenv.config(); const app = express(); // Middleware app.use(cors()); app.use(express.json()); // Database connection mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); mongoose.connection.once('open', () => { console.log('MongoDB database connection established successfully'); }); // Routes app.use('/api', require('./routes')); // Start server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
In this file, we:
- Import necessary dependencies.
- Load environment variables using
dotenv
. - Initialize an Express app and configure it with the
cors
andexpress.json
middleware. - Connect to the MongoDB database using
mongoose
. - Set up a route for the API and import the routes from the
routes
folder. - Start the server on the specified port.
Creating a Sample Model, Controller, and Route
To demonstrate how the backend works, let's create a simple model, controller, and route.
Model
In the models
folder, create a file named user.js
and add the following code:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, }); module.exports = mongoose.model('User', userSchema);
Here, we define a simple user schema with name
and email
fields.
Controller
In the controllers
folder, create a file named userController.js
and add the following code:
const User = require('../models/user'); exports.createUser = async (req, res) => { try { const user = new User(req.body); await user.save(); res.status(201).json(user); } catch (error) { res.status(400).json({ message: error.message }); } };
This controller exports a single function, createUser
, which creates a new user using the request's body and saves it to the database.
Route
In the routes
folder, create a file named index.js
and add the following code:
const express = require('express'); const router = express.Router(); const userController = require('../controllers/userController'); router.post('/users', userController.createUser); module.exports = router;
Here, we set up a single route that maps the /users
endpoint to the createUser
function in the userController
.
Testing the Backend
To test the backend, run the following command:
node backend/app.js
You should see the following output:
Server is running on port 5000
MongoDB database connection established successfully
Now, you can use a tool like Postman or Insomnia to test the /api/users
endpoint.
Setting Up the Frontend
Creating a React Application
We will use create-react-app
to bootstrap our React application. Run the following command:
npx create-react-app frontend
Once the installation is complete, navigate to the frontend
folder:
cd frontend
Installing Additional Dependencies
Install the necessary dependencies for our frontend by running the following command:
npm install axios
axios
is a library that simplifies making HTTP requests from the browser.
###Creating Components and Connecting to the Backend
Let's create a simple form to add users to our database. In the frontend/src
folder, create a new folder named components
. Inside the components
folder, create a file named UserForm.js
and add the following code:
import React, { useState } from 'react'; import axios from 'axios'; const UserForm = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post('http://localhost:5000/api/users', { name, email, }); console.log(response.data); setName(''); setEmail(''); } catch (error) { console.error(error); } }; return ( <form onSubmit={handleSubmit}> <label htmlFor="name">Name:</label> <input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} /> <label htmlFor="email">Email:</label> <input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <button type="submit">Add User</button> </form> ); }; export default UserForm;
This component consists of a form with two input fields, one for the user's name and the other for the user's email. The handleSubmit
function sends a POST request to the /api/users
endpoint with the user's name and email as the payload.
Integrating the UserForm Component
Now, let's integrate the UserForm
component into our application. Open the frontend/src/App.js
file and modify it as follows:
import React from 'react'; import UserForm from './components/UserForm'; function App() { return ( <div className="App"> <h1>Create User</h1> <UserForm /> </div> ); } export default App;
Running the Application
Start the frontend development server by running the following command:
npm start
The React application should now be running at http://localhost:3000
. You can use the form to create users, which will be saved in the MongoDB database.
Conclusion
In this blog post, we have learned how to build a full-stack MERN application, covering everything from setting up the development environment to creating a simple React component that interacts with our backend API. The MERN stack is a powerful toolset that allows you to build scalable and feature-rich applications with ease. With this knowledge, you can now go forth and create your own MERN applications, expanding upon the concepts and code examples provided here.
Sharing is caring
Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: