How to Build and Deploy Your First Full-Stack Application Using the MERN Stack
The MERN stack (MongoDB, Express.js, React, Node.js) is a powerful and popular technology stack for building full-stack web applications. It offers developers the flexibility to work on both the frontend and backend using a single language: JavaScript. If you’re a new developer, learning the MERN stack is a fantastic way to get hands-on experience with building and deploying modern web applications.
In this blog post, we’ll walk through building and deploying your first full-stack application using the MERN stack. We’ll cover everything from setting up your development environment to deploying your application online.
What is the MERN Stack?
The MERN stack consists of four key technologies:
- MongoDB: A NoSQL database used to store application data.
- Express.js: A lightweight framework for building backend services and APIs in Node.js.
- React: A JavaScript library for building interactive user interfaces on the frontend.
- Node.js: A JavaScript runtime that allows you to build the backend server and handle server-side logic.
Together, these technologies create a seamless environment for building full-stack applications that are both powerful and scalable.
Prerequisites
Before we dive into building your first MERN stack application, make sure you have the following prerequisites:
- Node.js and npm installed (you can download them from Node.js official website).
- Basic knowledge of JavaScript and React.
- Familiarity with Git for version control (optional but highly recommended).
Step 1: Set Up Your Development Environment
Start by setting up your project directory and initializing a new Node.js project:bash
This will create a new project folder named mern-app and initialize a package.json file.
Next, install the necessary dependencies for the backend:
npm install express mongoose dotenv cors
npm install nodemon --save-dev
- Express: A web framework for Node.js to create backend routes and APIs.
- Mongoose: An ODM (Object Data Modeling) library for MongoDB to interact with the database.
- dotenv: A package for managing environment variables.
- cors: Middleware to handle Cross-Origin Resource Sharing.
- nodemon: A tool to automatically restart your server when files change (for development purposes).
Step 2: Build the Backend with Node.js and Express
Create a server.js file in your project’s root directory. This will serve as the entry point for your backend server. Here's a basic setup:
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.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Sample route
app.get('/', (req, res) => {
res.send('Hello, MERN Stack!');
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
});
MongoDB Setup
Before starting the server, you need to set up a MongoDB database. You can either install MongoDB locally or use MongoDB Atlas, a cloud-based solution.
- Create a new MongoDB database and copy the connection URI.
- In your project’s root directory, create a
.envfile and add the following:
MONGO_URI=your_mongodb_connection_string
Run the Server
To start the server, use nodemon so it automatically restarts on file changes:
npx nodemon server.js
If everything is set up correctly, you should see Server running on http://localhost:5000 in your terminal.
Step 3: Build the Frontend with React
Now, let's create the frontend using React. In the mern-app directory, run:
npx create-react-app client
This command sets up a new React application in a client folder. Change to this directory and start the React development server:
cd client
npm start
You should see the default React application running at http://localhost:3000.
Connect React and Express
To connect the React frontend with the Express backend, you’ll need to make some changes:
- In the
clientdirectory, install axios, a promise-based HTTP client:
npm install axios
- Update
package.jsonin the client folder to set up a proxy:
"proxy": "http://localhost:5000"
- Create a new file called
App.jsin theclient/srcfolder and replace its contents with:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
const [message, setMessage] = useState('');
useEffect(() => {
axios.get('/')
.then(response => setMessage(response.data))
.catch(error => console.log(error));
}, []);
return (
<div className="App">
<h1>{message}</h1>
</div>
);
};
export default App;
This code sends a GET request to the backend and displays the response.
Step 4: Deploy Your MERN App
Once your app is working locally, the next step is to deploy it. We’ll use Heroku for the backend and Netlify for the frontend.
Deploying the Backend with Heroku
- Sign up for a Heroku account and install the Heroku CLI.
- In the root of your project (where
server.jsis), initialize a new Git repository:
git init
- Commit your code and create a new Heroku app:
git add .
git commit -m "Initial commit"
heroku create mern-app-demo
- Set up environment variables in Heroku:
heroku config:set MONGO_URI=your_mongodb_connection_string
- Deploy your app:
git push heroku main
Your backend should now be live on Heroku.
Deploying the Frontend with Netlify
- In the
clientdirectory, build the React app:
npm run build
- Go to Netlify and sign up for an account.
- Drag and drop the
client/buildfolder onto Netlify, and your frontend will be live in seconds!
Conclusion
Congratulations! You’ve just built and deployed your first full-stack application using the MERN stack. By following this guide, you’ve gained hands-on experience with backend development using Express and Node.js, database management with MongoDB, and frontend development with React. You also learned how to connect and deploy these components using Heroku and Netlify.
The MERN stack is a powerful and versatile framework for building modern web applications. With these skills, you’re well on your way to developing complex and scalable applications in the real world. Happy coding!

Comments
Post a Comment