Learn in very simple steps connecting Node with React or ReactJS in this blog. While we use both web development languages then they form a stack known as the MERN stack. This blog is written by our MERN student for beginners and reviewed by senior Node and React faculty Mr. Ravi Bhaduaria.
Step-by-Step Guide on MERN Setup for Beginners
Our focus is on the basics of the setup of Node, React, project structure, and testing. We will cover the hosting of a Node and MERN app also in this blog.
Let’s get started.
Know about the React.js
- What It Is: A library written in JavaScript for developing user interfaces using the approach of single-page apps. Those who understand JavaScript can understand the fundamentals of ReactJS easily.
- Key feature: For quick updating and rendering, it makes use of virtual DOM and reusable components.
Exploring the basics of Node.js
- What It Is: A server-side runtime environment for JavaScript.
- Important feature: Its event-driven, non-blocking I/O architecture makes it perfect for real-time, scalable applications.
What is the MERN or MERN Stack?
Full-stack JavaScript programming is made possible by Node.js handling the server-side back end and React handling the user interface (UI). When we use Node.js with React.js, it becomes MERN or MERN stack.
MERN stack has achieved high popularity recently due to its ease and simplicity.
Why MERN is easy to learn?
As we said above, Node and React are JavaScript. It means that the base language of these two is JavaScript. So, the syntax MERN stack uses is from JavaScript. You don’t need to learn a new syntax for the MERN, and it makes it easy to use.
JavaScript is lightweight and its apps run very fast. It makes it very easy to deal with all major lifecycle stages of an app like coding, debugging, and testing.
Those who want to learn MERN and MEAN can explore our courses in MERN Stack and MEAN Stack development.
How to connect Node with React
Setting up a full-stack web application entails connecting Node.js and React. Node.js maintains the back-end, which includes server-side logic, database operations, and API routes. On the other hand, React takes care of the front end. React renders the user interface and communicates with the back end through HTTP requests. This comprehensive guide explains how to integrate React with Node.js.
1. Setting Up the Project Structure
The very first thing is to set up a directory structure that arranges the front-end and back-end components. Creating a root project folder with two subfolders—one for the React front-end (client) and another for the Node.js back-end (server)—is a typical method.
/my-app
/server
/client
Back end (Node.js) Setup
Initiate a new Node.js project in the server folder:
mkdir server
cd server
npm init -y
A package.json file, which controls scripts and dependencies, will be created as a result. Installing required packages is required. Express.js, for example, will handle HTTP requests. Other dependencies, such as Cors for cross-origin resource sharing and Mongoose if you’re using MongoDB, must also be installed.
npm install express cors mongoose
Front-end (React) Setup
create-react-app is a popular toolchain for bootstrapping React apps. It lets you create a React application inside the client folder.
npx create-react-app client
This will create a default React project structure. It will include all the components you need to get the front end built.
2. Developing the Back-end (Node.js with Express)
First, let’s build a basic Express server that will function as your application’s API. Make the following file, index.js, in the server folder:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
// Initialize Express app
const app = express();
// Middleware
app.use(cors()); // Enable CORS
app.use(express.json()); // Parse JSON bodies
// Connect to MongoDB (if you're using it)
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Sample route
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from the backend!' });
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Explanation of the Code
- To create a server that listens on a given port, use Express.
- Through the use of middleware known as CORS, communication between the front-end and back-end is made possible. Both ends operate on separate ports in your project.
- To connect to a MongoDB database, use Mongoose; if you’re using a different database, skip this step.
- An example of an API endpoint that returns a JSON response is the /api/data route. The React front end will make use of this path.
3. Developing the Front-end (React)
Open the App.js file in the client folder and make changes to it to retrieve data from your Node.js back-end.
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data from the backend
fetch('http://localhost:5000/api/data')
.then((response) => response.json())
.then((data) => setData(data.message))
.catch((error) => console.error('Error fetching data:', error));
}, []);
return (
<div className="App">
<header className="App-header">
<h1>{data ? data : 'Loading...'}</h1>
</header>
</div>
);
}
export default App;
Explanation of the Code
- React hooks include useEffect and useState. UseEffect takes care of side effects like data fetching, whereas useState maintains the component’s state.
- A GET request is sent to the Node.js back end using the fetch method. If the data retrieval is successful, the component displays and stores the data in the data state.
4. Running and Testing the Node Application
You must run both the front-end and back-end servers to test the connection between Node.js and React.
Running the Back-end of Node
Launch the Node.js server from the server folder:
node index.js
The back end will launch at http://localhost:5000 as a result.
Running the Front-end
Launch the React development server from the client folder:
npm start
The React application will launch at http://localhost:3000 as a result.
Now, the message retrieved from the Node.js back-end should be displayed in the React application when you visit http://localhost:3000 in your browser. When everything is configured properly, the screen will say “Hello from the back end!”
5. Handling Different Environments
You’ll have to manage several settings in a real-world program, including development, testing, and production. Here’s how to handle the Node.js and React connection in various contexts.
Environment Variables
Environment variables are a useful tool for configuring various settings for various environments. For instance, make a.env file inside the React application:
fetch(`${process.env.REACT_APP_API_URL}/data`)
You can then utilize this variable in your React components:
fetch(`${process.env.REACT_APP_API_URL}/data`)
With this method, you can modify the API URL according to your requirements without requiring it to be hard coded.
Proxying API Requests
CORS problems may arise because React’s development server uses a different port than the Node.js server when it is being developed. Using a proxy is one approach to make this setup simpler.
Include a proxy configuration in the client/package.json file:
"proxy": "http://localhost:5000"
This setup will automatically forward any /api/… API request from the React app to http://localhost:5000/api/…, saving you from having to provide the complete back end URL in your fetch requests.
6. Deploying the Node and React Application
The front-end and back-end of your application are frequently served by the same server when it is deployed to production. Here’s how to go about it.
Serving React from Node.js
Your Node.js server should probably be used to deliver your React front-end directly in a production setting. Building your React application and setting up Node.js to serve the static files are required steps in this process.
Make a production build of your React application first:
cd client
npm run build
This will produce the optimized front end files in a build directory.
const path = require('path');
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build', ‘index.html'));
});
React Router can handle client-side routing using this setup, which returns the index.html file for the React app in response to any request that doesn’t match an API route.
Deploying to a Live Hosting Service
There are multiple options to deploy your MERN app such as Heroku, DigitalOcean, and AWS. Once your MERN app is configured, you are ready to serve all. The same server will serve both the front-end and back-end.
For example, to deploy to Heroku, the following steps must be taken:
i. Open the root directory and create a Procfile:
web: node server/index.js
ii. Upload your program to Heroku:
git init
heroku create
git add .
git commit -m "Deploying MERN stack app"
git push heroku master
Heroku will install the dependencies, launch your application, and detect the Node.js environment automatically.
Final Words on Connecting Node with ReactJS
Connecting Node.js with React is not a difficult task but a crucial ability. You now know how to develop a simple MERN stack application with React and Node. React will be handling the front end and Node.js and Express will handle the back end. Connecting these two techs is not enough you should learn advanced concepts of Node.js, React, and MERN development.
Additionally, you’ve dived into the deploying process of the Node and React program. We also understood the steps involved in maintaining several settings. Using the MERN stack, this configuration serves as the basis for creating dependable, scalable online applications.
Want to Master Node and ReactJS?
Follow the path of smart learning from experts with well-planned programs in website design. At ADMEC, we offer multiple courses in both Node and ReactJS for learners of different levels. Some of the main courses are:
It is recommended for developers who are already working on HTML, CSS, Bootstrap, and JavaScript. This course focuses on the high-level features of ReactJS and its integration with Firebase, NPM, Redux, etc.
It is important for learners to have JavaScript knowledge. This course targets the development of single-page applications using Redux and Firebase.
Recommended for beginners who know the basics of JavaScript and want to learn React from a very basic level.
This program is planned for all learners who want to master back-end development with Node. Even if you are not a JavaScript expert and know HTML and CSS only, you can still pursue this program.
Most recommended for web developers who work on front-end as well as back part and want to upgrade their skills.
A short-duration course covering the basics of Node.js.
Start your learning journey with ADMEC Today!
Want to read more about React and Node?
Check out other blogs:
- Top 5 Books of Node.js
- React or Angular – Which is best for a beginner?
- Why Node JS is best for beginners?
- Strengths and Weaknesses of PHP, Python, and Node.js
- 5 Strong Reasons: Why You Should Learn Node.js for Web Development
- Python vs Node.js – Practically Explained
- Will PHP be History Soon Because of Python and Node.js?