How to Build a Full-Stack Application With MERN
Building a full-stack application using the MERN stack—MongoDB, Express.js, React.js, and Node.js—can seem daunting at first, but with the right approach, it’s a manageable and rewarding process. This guide will walk you through the essential steps to create a robust and scalable application.
Step 1: Setting Up Your Environment
Before you start coding, you'll need to ensure that your development environment is properly set up. This means having Node.js and npm (Node Package Manager) installed on your machine. You can download them from the official Node.js website. Additionally, make sure to have MongoDB installed either locally or use a cloud solution like MongoDB Atlas for your database.
Step 2: Initializing Your Node.js Backend
Start by creating a new directory for your project and initializing it with npm:
mkdir my-mern-app
cd my-mern-app
npm init -y
Next, install the necessary backend dependencies:
npm install express mongoose cors dotenv
Then, create a file named server.js
. This will be the main entry point for your application:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
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));
// Sample route
app.get('/', (req, res) => {
res.send("Hello from the server!");
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 3: Creating the React Frontend
Now that you have your backend set up, it's time to create the React frontend. In another terminal, navigate to your project folder and create a React app:
npx create-react-app client
Change into the client
directory:
cd client
Once in the client directory, install Axios for handling HTTP requests:
npm install axios
Now, modify the src/App.js
file to create a simple fetch request from your backend:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
const [message, setMessage] = useState('');
useEffect(() => {
axios.get('http://localhost:5000/')
.then(response => {
setMessage(response.data);
})
.catch(error => {
console.log(error);
});
}, []);
return (
{message}
);
};
export default App;
Step 4: Connecting Frontend and Backend
To connect your frontend and backend, ensure your backend server is running by executing:
node server.js
Then, navigate back to the client
directory and start your React application:
npm start
Visit http://localhost:3000 in your browser; you should see your message from the server displayed on the page.
Step 5: Deploying Your MERN Application
Once you've completed development, you may want to deploy your application. Common options include Heroku for the backend and deploy your React client separately or integrate them using a service like Vercel or Netlify.
Ensure you build your React app for production by running:
npm run build
This will create a build
folder in your client
directory. You'll configure your Express server to serve the static files in this folder.
Conclusion
Developing a full-stack application with the MERN stack allows you to utilize JavaScript across the entire