Clue Mediator

How to deploy a react app to node server

šŸ“…March 29, 2020

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

  1. file">Create server file
  2. Create react application
  3. Create a build of react application
  4. 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

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.

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.

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.

npm i forever -g

Now execute the following command to run the server continuously.

forever start server.js

If you are working with the windows system then run the following command.

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!