What is the best way to combine a React App and an Express App in order to deploy them as one

After successfully creating an Express and MongoDB API and connecting it to my React Application, I encountered a situation during deployment. It seems that I need to deploy both projects separately, which means I would need two hosting plans for them. However, I would prefer to have both projects running on the same host. Is this possible? If so, how can I achieve this?

Answer №1

When a React application is built, it generates static files as output, including script bundles and .html files that reference the bundles using <script> tags (unless webpack-dev-server is used for compilation).

It is important to copy these files to an Express server in a production build, consolidating everything into one server on one host. This setup ensures that the React application running in the client side, such as a browser, can access all necessary elements – .html files, script bundles, and API responses – from just one source: the Express backend/server. This also eliminates the possibility of encountering CORS issues often discussed on platforms like Stack Overflow.

For example, you can explore a boilerplate project showcasing this setup.
To run the project:

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

After executing these commands and directing your browser to localhost:3000, you will see the React app functioning within your browser, fetching resources exclusively from the cohesive Express backend.

The crisp-react project includes two subdirectories: client containing the React client app and server housing the Express backend. During the build process, artifacts are seamlessly transferred between these subdirectories. This means that you can even modify or remove the client subdirectory post-build without affecting the operational state of the Express backend.

Answer №2

If you want your Express server to serve the build/dist folder from your React/Frontend/Client, you have a couple of options. You can either configure your express server to directly serve the build folder or have it build directly into the express folder. This setup also works seamlessly with webpack. Here's an example of how you can achieve this:

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

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

// Pointing to the build folder of your React app
app.use(express.static("../app/dist"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jest.fn prop is not triggering the mock function as expected

Exploring the select feature of a component, I'm currently testing it using https://www.npmjs.com/package/react-giphy-searchbox This is how I've implemented it: GifSection.tsx import React, { Fragment } from "react"; import ReactGiph ...

Delete element from the array upon removal from the AutoComplete component

I am facing a challenge with the Material UI AutoComplete component in my project. The issue arises when I try to update the state of the associateList after clearing a TextField. Additionally, I would appreciate any guidance on how to handle removing an ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

Remove an element from an array within an object stored in a MongoDB document

Greetings and thank you for taking the time to read my query! I am currently diving into the world of coding, and here's my first question on this platform: I have a MongoDB collection structured similarly to the example below. Each document represe ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

The Fetch API seems to be having trouble loading the data from localhost:300

I am facing an issue with my express-js server that returns an array of data. I want to use the Fetch API to make a request and display this list on the screen. However, every time I try to make a request, I encounter an error stating "Fetch API cannot loa ...

React troubleshooting: NPM crashing error

Attempting to set up and run a react project on the same machine where Angular applications are working properly, but encountering an error when running npm start. The error stack is as follows: 0 info it worked if it ends with ok 1 verbose cli [ ' ...

Encountering a passport error in Node.js - how to troubleshoot and

I'm currently experimenting with using passport in Node for some basic tests. Whenever I attempt to access the route localhost:3000/login, I encounter a Bad Request 400 error. Here's the snippet of code that is causing the issue: var express = r ...

Issue with React Redux: Store dispatch not causing component update

I have recently implemented React Redux in my project, but I seem to be encountering some issues. Despite changing the state, the value remains the same. I attempted to use useStore(), but it does not take any parameters. Can anyone provide insight into wh ...

The Node.js server gracefully operates on both the 0.0.0.0 and localhost ports without encountering any issues

I've come across something intriguing that has me stumped, and my attempts to Google it were not fruitful. On one hand, I have an Express server named server 1, linked to localhost: const express = require('express') const app = express() ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

What is the best method to calculate the total of one entry per day over the course of a

I'm attempting to calculate the total values for each day in a month, but I only want to sum up one entry per day throughout the month. I tried using $limit before the group function, however, it only returned one entry. Thank you. [ { $ ...

How can I use React JS to restrict a textbox to only accept numbers and format input as a US mobile number format like (224) - 5623 -2365?

I am currently working on mobile number validation with React. My goal is to allow only digits and format the input as a US mobile number. Although I am successfully restricting the input to only digits, I am facing an issue with formatting. For this tas ...

Cannot perform mapping within an asynchronous function

Within the following snippet of code, I am retrieving information from an external api. When converting the data to json format, my intention was to loop through it and generate a modified version. Interestingly, the console.log(jsonData) within the map f ...

Merging row data by their corresponding ids from multiple tables within a database

example_table_1 id | user_id | morning 1 | 1 | banana example_table_2 id | user_id | afternoon 1 | 1 | mango example_table_3 id | user_id | evening 1 | 1 | watermelon These are merely sample tables that I would like to combine ...

The call is not being answered by the server route (NodeJS + express)

I have encountered an issue while setting up a server using NodeJS and Express. When I attempt to make a get request to the basic route ('http://localhost:3000/'), the request seems to hang indefinitely. Despite thoroughly reviewing my code multi ...

Display a Next.js website page in an overlay

I have a website that includes a search function. What I want to achieve is for the user to be able to click on a search result and have the product open in an overlay instead of having the entire page reload. However, I also want the URL in the address ba ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...