Combining React and Node Full Stack Projects Together
Real life applications on the web are usually made of the frontend and the backend. Deploying those sides of the application may require paying double the amount of one. In this article you'll learn how to combine your ReactJS and your NodeJS applications into one for deployment.
But to fully understand this article you will need to have knowledge of NodeJS, ReactJS and Express.
What is a Full Stack Application?
These are applications that have both a frontend and a backend. They are also not complete with just one of the sides. In these applications the front end sends a request to the backend to either process it or to store data. These applications provide more functionality to frontend applications by utilizing the power of a backend with the ease of use of a frontend.
- They allow users to store some type of data on a web application.
- Business owners track the activities of the users of their product when it is full stack.
- These types of applications are able to connect different users together.
They are able to perform much more than what is listed here.
Creating the Demo Backend
We will start our full stack application by creating our demo backend api that our frontend will communicate with. We start our application by installing the packages that will be necessary to our project.
npm install express cors
Express is a simple and lightweight framework for building static web pages and backend APIs. And cors is an express middleware that allows an external frontend application communicate with our api. This would be useful for development of a full stack application, but can be removed when we are preparing for deployment.
After installing the necessary packages, we create a new index.js file where we will be writing our APIs.
And write the following into it;
const cors = require('cors'); const express = require('express'); const app = express(); app.use(cors()); app.get('/api/hello', (req, res) => { res.send('This is my hello'); }); app.listen(8000, function() { console.log("listening on port: 8000"); });
Here is an explanation of what is going on in this code;
- In the 1st and 2nd line, we imported our recently installed packages, express and cors.
- Then, we create our app in the 3rd line.
- After creating the app, we add the cors middleware in the 5th line.
- Then register an endpoint that our frontend will talk to in the 7th - 9th lines.
- Finally, we set up a listener on the port 8000 that our application will be hosted on the 11th - 13th lines.
Then we run our application using the command below in our terminal.
node index.js
Then we enter "http://localhost:8000/api/hello" in our browser to see the application.
The Demo Frontend
Now that we have our backend setup, it's time to create the frontend application that our application will be communicating with. This frontend application is going to communicate with the /api/hello endpoint of the backend. So we'll start with an empty react project.
npx create-react-app frontend
After creating the project, navigate to the frontend folder. In this folder, create two files .env.development and .env.production. These are where we will keep our production and development environment variables used by ReactJS. In the .env.development file write the following.
REACT_APP_BACKEND=http://localhost:8000/
And in the .env.production file write the following into it.
REACT_APP_BACKEND=/
This will be used by ReactJS to connect to the backend in the two environments.
After setting the environment variables, we navigate to the src folder and open the App.js file. Then, write the following into it.
import {useState, useEffect} from 'react'; function App() { let [response, setResponse] = useState(""); useEffect(() => { fetch(process.env.REACT_APP_BACKEND + "api/hello") .then(response => response.text()) .then(text => setResponse(text)); }, []); return <div>The server says: {response}</div>; } export default App;
How this code works is explained here.
- We import the useState and useEffect hooks from the react project on the 1st line.
- On the 3rd all through to the 15th line, we created our component.
- Then, we export the component using export default App; on the last line.
In the component we did the following.
- We created a response state variable for storing our backend's response on the 1st line.
- Then, On the 3rd - 8th line, we use the useEffect hook to communicate with our backend and set the response state variable.
- We use the REACT_APP_BACKEND environment variable to locate the backend on the 4th line.
- Finally, we return a react component that will display the response from the backend.
Combining them
Now that we have the two projects built, it is time to combine them into one. Before we do, we need to prepare the frontend for production. We do this with the following in the terminal in the frontend folder.
npm run build
This will create a build folder that can be used for production. Then, we move that folder into our backend project. After moving the folder, we add static rendering with the express.static() middleware function. We use static rendering to display web pages within our backend.
app.use(express.static('build'));
The 'build' in the snippet above points to the build folder in our project. That makes the index.js look like the following now.
const cors = require('cors'); const express = require('express'); const app = express(); app.use(cors()); app.use(express.static('build')); app.get('/api/hello', (req, res) => { res.send('This is my hello'); }); app.listen(8000, function() { console.log("listening on port: 8000"); });
We can now run our application and see what we get in our browser.
Conclusion
In this article, we saw how environment variables can be used to simplify the process of switching environments. And, we saw how static rendering can be used to render web pages alongside the creation of APIs. I hope this article gives a clear understanding of how we can combine both sides of a full stack React-Node application together.
If any part of this article seems complicated or hard to understand, be sure to let me know in the comment section. Thanks for reading, and happy hacking!
Awesome!!
ReplyDeleteCool and easy to understand
ReplyDelete