How to deploy a react app to node server
In this article, we’ll show you how to deploy a react app to node server. Most of the developers know about setup react applications but some of them have always confusion about the deployment of the react application on production servers. So today I will give you a step by step explanation to deploy a react project.
How to deploy a react app to node server, Deploy Create-React-App with Express, Set up a React app with a Node.js server, How to deploy a React + Node app, Building and Deploying a React Frontend with a Node backend, Deploying ReactJS application in production, How to host react app and node api on server, connect server to react app, how to setup react and node js in a project.
Checkout more articles on ReactJS
Step to deploy a react app to node server
- Create server file
- Create react application
- Create a build of react application
- Use npm package to run the server continuously
1. Create server file
Let’s start with creating a directory name as deploy-react-app
where we will manage the server file and react application.
In the next step, create a server file as server.js
within the directory.
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const express = require("express"); const path = require("path"); const app = express(); const port = process.env.PORT || 4000; // serve static files built by React app.use(express.static(path.join(__dirname, "test-app/build"))); app.get("/", function(req, res) { res.sendFile(path.join(__dirname, "test-app/build", "index.html")); }); app.listen(port, () => { console.log('Server started on: ' + port); }); |
In the above code, test-app
is the name of a react application which we’ll create in the next step.
Also, we will serve the application on 4000
port. Make sure if you don’t have express installed in your system then install it.
2. Create react application
Now let’s create a react application using create-react-app
. Run the following code to create a react application.
1 | npx create-react-app test-app |
3. Create a build of react application
In the next step, create a build of react application by running the following command.
1 | npm run build |
You can see the newly created build
folder in the root directory.
4. Use npm package to run the server continuously
At last, we are going to use the forever npm package to run the server continuously.
Run the following command to install the package. Here we will globally install the package.
1 | npm i forever -g |
Now execute the following command to run the server continuously.
1 | forever start server.js |
If you are working with the windows system then run the following command.
1 | forever start -c node server.js |
After successful execution, you can check the link http://localhost:4000/
.
Here is the list of commands that will help you to manage the server.
That’s it for today.
Thank you for reading. Happy Coding!