Full-stack Web Application with MERN

How to Build a Full-Stack Web Application with MERN Stack

If you’re looking to build a full-stack web application, I’ve found that the MERN stack is an excellent choice. It’s composed of four powerful technologies: MongoDB, Express.js, React, and Node.js, all working together to create seamless and scalable web applications. In this post, I’ll walk you through how to set up and build a complete MERN stack application from scratch, covering everything from the back-end to the front-end.

By the end of this guide, you’ll have a fully functional app, and more importantly, you’ll understand how each of these technologies works together to create a cohesive system. So, let’s dive right in!

Full-stack Web Application with MERN

Full-stack Web Application with MERN

What is the MERN Stack?

Before we jump into the actual coding, let me quickly explain the four key technologies that make up the MERN stack:

  • MongoDB: A NoSQL database that uses a flexible, JSON-like format to store data. It’s known for its scalability and is perfect for modern web apps.
  • Express.js: A minimalistic framework for Node.js that simplifies handling HTTP requests and routing. It helps you build the back-end of your app quickly.
  • React: A popular JavaScript library for building user interfaces, particularly Single Page Applications (SPAs). React is component-based, which makes it highly reusable and easy to maintain.
  • Node.js: A JavaScript runtime environment that lets you execute JavaScript code on the server-side, enabling you to use JavaScript for both the front-end and back-end.

Together, these technologies form a powerful stack that is ideal for developing modern web applications.


Setting Up the Development Environment

Step 1: Install Node.js and npm

To get started, I need to have Node.js and npm (Node Package Manager) installed on my machine. Node.js is essential because it’s the environment where my back-end code will run, and npm will help me manage all the libraries I need for the project.

  1. Download and install Node.js from the official website.
  2. After installation, open your terminal and check the versions of Node.js and npm with:bashCopy codenode -v npm -v

You should see the versions of Node.js and npm displayed.

Step 2: Install MongoDB

For the database, I’m using MongoDB. You can either install it locally or use a cloud-based solution like MongoDB Atlas, which makes it easier to manage your database.

  1. If you want to install MongoDB locally, download it from MongoDB Community Edition.
  2. If you’re using Atlas, you can set up a free cluster by following the instructions on their website.

Once MongoDB is installed or set up on Atlas, I’ll get the connection string that I’ll use to connect my back-end server to the database.


Setting Up the Back-End with Node.js and Express

Step 3: Initialize the Project

Now it’s time to start the back-end of my application. I’ll begin by creating a new directory for my project and initialize it with npm.

bashCopy codemkdir mern-app
cd mern-app
npm init -y

This will create a new project and generate a package.json file.

Step 4: Install the Required Dependencies

Next, I’ll install the essential back-end dependencies using npm:

bashCopy codenpm install express mongoose cors dotenv
  • express: A web framework for Node.js that simplifies routing and middleware.
  • mongoose: An Object Data Modeling (ODM) library for MongoDB, which makes working with MongoDB data easier.
  • cors: A package that allows Cross-Origin Resource Sharing (CORS), which is necessary for allowing my React front-end to make API requests to the back-end.
  • dotenv: A package that helps manage environment variables (e.g., my MongoDB URI) securely.

Step 5: Set Up the Express Server

With the dependencies installed, I’ll now create a server.js file where I’ll set up my Express server:

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

const app = express();

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

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

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

// Server listening
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

This sets up the server and connects it to MongoDB using the connection string stored in the .env file.

Step 6: Set Up Environment Variables

To keep my MongoDB URI secure, I’ll use environment variables. I’ll create a .env file in the root of my project:

envCopy codeMONGODB_URI=your_mongodb_connection_string
PORT=5000

I’ll replace your_mongodb_connection_string with the actual MongoDB URI from Atlas or my local MongoDB setup.


Building the Front-End with React

Step 7: Create the React Application

Now that my back-end is ready, it’s time to create the front-end using React. I’ll navigate to the root of my project and use Create React App to set up a new React project:

bashCopy codenpx create-react-app client
cd client
npm start

This creates a client folder and runs the React development server on http://localhost:3000.

Step 8: Install Axios for HTTP Requests

To make HTTP requests from React to my Express server, I’ll use Axios, a popular HTTP client. I’ll install it by running:

bashCopy codenpm install axios

Step 9: Set Up React Components

Now, I’ll set up a simple React component that fetches data from the back-end API.

In the src folder of my React app, I’ll modify the App.js file to look like this:

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

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    axios.get('http://localhost:5000/')
      .then(response => {
        setMessage(response.data);
      })
      .catch(error => console.error('There was an error!', error));
  }, []);

  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}

export default App;

This code uses axios to send a GET request to the back-end and displays the response in the front-end.


Connecting the Front-End and Back-End

Step 10: Enable CORS

Since the front-end and back-end are running on different ports, I need to ensure that CORS (Cross-Origin Resource Sharing) is properly set up. I’ve already done this by adding app.use(cors()) in the Express server.

Step 11: Test the Application

Finally, I’ll test everything to make sure it works as expected.

  1. In one terminal, I’ll run the back-end server:bashCopy codenode server.js
  2. In another terminal, I’ll run the React app:bashCopy codenpm start

Now, if I open my browser and navigate to http://localhost:3000, I should see the message from the back-end server displayed in my React app.


Conclusion

And there you have it! I’ve just walked you through building a full-stack web application using the MERN stack. With MongoDB handling the data, Express managing the back-end, React building the user interface, and Node.js running the server, this stack is perfect for modern web development.

The best part? All these technologies work seamlessly together, making the development process faster and more efficient. Now that you have the basic app up and running, you can enhance it by adding features like user authentication, state management with Redux, or deploying it to platforms like Heroku.

Full-stack Web Application with MERN

Happy coding, and I hope this guide helped you take your first steps into building full-stack applications with the MERN stack!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *