RinMori
RinMori

Reputation: 61

How to merge React App and Express App to deploy on single project?

I recently create Express and MongoDB API and after that, I connect that API to my React Application successfully and which is running well. But one situation occurring during deployment now I need to deploy both projects separately means I need two hosting plan for them. So, I want that both project running on the same host. Is it possible? and How?

Upvotes: 0

Views: 776

Answers (2)

Janspeed
Janspeed

Reputation: 2814

Basically you can let your express server serve the build/dist folder from your React/Frontend/Client and serve it in express or make it build directly into your express folder. Works with webpack as well. Something like this:

const express = require("express");
const app = express();
const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Listening on port ${port}`));

//The path to your react app build folder
app.use(express.static("../app/dist"));

Upvotes: 0

winwiz1
winwiz1

Reputation: 3164

A build of any React application creates (unless webpack-dev-server is used to compile it) the output which consists of static files: script bundles and .html file(s) that reference the bundles in <script> tag.

Those files can and should be copied to Express in production build. Then you have one server on one host. When React application runs inside a client (e.g. browser) it gets everything including .html files, script bundles, API responses from the single source: Express backend/server. Which by the way excludes any possibility of getting CORS issues so many people are asking about here on SO.

Example, e.g. a boilerplate project that demonstrates all that.
If you execute commands:

git clone https://github.com/winwiz1/crisp-react.git
cd crisp-react
yarn install && yarn start:prod

and then point your browser to localhost:3000, you will have React app running inside your browser and it got everything from one single Express backend.

crisp-react has two subdirectories: client with React client app and server with Express backend. The build command copies the build artifacts from one subdirectory to another. So you can even rename or delete the client subdirectory after a build, it won't affect the Express backend.

Upvotes: 2

Related Questions