I am experiencing an issue with my React app deployed on Heroku where it successfully loads the home page but fails

My react application performs perfectly when run locally and is successfully deployed on heroku. However, upon clicking any link from the home page to another page, a blank page with 'not found' message appears. No other error messages are displayed.

The server-side package.json file is as follows:

{
  "name": "portfolio-generator",
  "version": "1.0.0",
  ...
}

Here's the client-side package.json:

{
  "name": "portfolio-generator",
  "version": "0.1.0",
  ...
}

server.js:

const express = require("express");
...
app.listen(PORT, () => console.log(`🌎  ==> API Server now listening on PORT ${PORT}!`));

I created a static.json file based on my research:

{
  "root": "build/",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}

The default route in routes/index.js on the server side:

....
module.exports = router;

In App.js (top component of react), react router is implemented like this:

...

Despite all efforts, I am unable to resolve the issue. The home page loads and refreshes but fails to redirect anywhere.

We discovered that the path to index.html was incorrect initially. It should be:

 router.use("*", (req, res) => res.sendFile(path.join(__dirname, "../client/public/index.html")));

However, after rectifying the path, only a blank screen appears on the heroku page. I suspect the problem lies in how the routes are defined but am still unable to identify it.

My folder structure is as follows:

/projectname
 /server.js
 /package.json
 ...
 /client
   /package.json
     /public
       index.html
     /src
       App.js
       index.js
       ...
         /components
         /pages
 /controllers
 /models
 /routes
     index.js
       /api
         index.js

After making critical changes in server.js, including adding the 'path' package and reordering the 'app.use(routes)' statement, the issue was resolved:

 const path = require('path');
 const express = require("express");
 ...
 app.get("*", function (req, res) {
   res.sendFile(path.join(__dirname, "./client/build/index.html"));
 });
 ...
 

Additionally, I removed the default react route reference in /routes/index.js

Answer â„–1

Success! Made 3 changes to server.js. Starting with:

const path = require('path')

Ah, a classic rookie mistake to forget this line! Additionally, relocated the default react route from the "production" code block and placed it below 'app.use(routes) like so:

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}
app.use(routes);
app.get("*", function (req, res) {
  res.sendFile(path.join(__dirname, "./client/build/index.html"));
});

Last but not least, removed the default react route from /routes/index.js.

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

Discover how to prevent a link or text from appearing if a user has already browsed a particular webpage

Is there a way to hide a link to another page if the user has previously visited that page? For example, I have 3 options - A, B, and C. If a user selects option A, links to pages B and C are displayed at the bottom of the page. However, if they then navi ...

What is the best method for adjusting the text size within a doughnut chart using react-chartjs-2?

Is there a way to adjust the text size within the doughnut chart using react-chartjs-2? I find that the center text appears too small. https://i.stack.imgur.com/QsI0V.png import React, {Fragment} from 'react'; import Chart from 'chart.js&a ...

Developing dynamic objects for input string fields in AngularJS

In my AngularJS view, I have the following setup: <label class="control-label">Name:</label> <input type="text" class="form-control" ng-model="config.name" /> <br /> <label class="control-label">versionSpecificApiConfig:&l ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Understanding the significance of the argument in the context of `express.json({ extended: false})`

Currently, I am in the process of setting up an API using express and encountered this particular line of code: app.use(express.json( { extended: false } )); Although I have referred to the documentation provided by express, I was unable to locate this sp ...

Monitoring multiple items in OPC UA with Node.js

Utilizing the node-opcua module, my goal is to efficiently monitor multiple opc ua nodes through subscriptions. The desired workflow involves a user selecting nodes in an HTML UI, clicking a Monitor button which then sends the corresponding nodeIds as para ...

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

What is the method for adding data to a table without utilizing an ID field?

Here is the code I have written: This table contains details of the candidates: <table id="candidates-table" class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Candidate Picture ...

testing exceptions with Jest: a step-by-step guide

As a beginner with Jest, I am currently working on a program to delve deeper into JavaScript. While my tests are functioning properly, I'm wondering if it would be better to replace the try/catch blocks with exceptions. I feel like there might be a mo ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

Is it necessary to execute `npx rnx-dep-check --init library` separately for each library within your project when using rnx-kit?

Currently, I'm following the instructions found in the manual for rnx-kit. In the Onboarding portion, it suggests creating the dependency manager configuration for your package by utilizing npx rnx-dep-check --init library. I have 20 packages listed i ...

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

Locating a record within a database that contains an objectId field linking to a separate collection

I have defined two collections in the following manner const BookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Object.Types.ObjectId, ref: "author" } }) const BookModel = mongoose.model(" ...

Having trouble with the `npm run dev` command in a Laravel project? You may be encountering a `TypeError: program.parseAsync is not

Recently, I integrated Vue.js into my ongoing Laravel project using npm to delve into front-end development with the framework. Following the installation, the instructions guided me to execute npm run dev in order to visualize the modifications made in . ...

Learn the process of submitting tag values using JohMun/vue-tags-input feature

I am a beginner in Vue.js and I am looking to implement an input field with multiple tags (user skills) using a Vue.js component. Although I have managed to make it work, I am struggling to figure out how to submit the tags in a form. Below is my code: T ...

"Discover the power of Next.js by utilizing dynamic routes from a curated list

I am working on a Next.js application that has a specific pages structure. My goal is to add a prefix to all routes, with the condition that the prefix must be either 'A', 'B', or 'C'. If any other prefix is used, it should re ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

What is the best way to show MUI's Autocomplete to feature the label from the corresponding value in props.options?

On my multilingual website, I am facing an issue with Autocomplete components. The options array needs to have its item labels translated, which is easily done. However, updating the currently selected value proves to be a challenge because Autocomplete u ...

Stop using Flexbox in Material UI on small screens

How can I prevent Flexbox from functioning on small screens using Material UI? I am looking for something similar to the d-md-flex class in Bootstrap but for Material UI. In Bootstrap (works as expected) <div class="d-md-flex align-items-md-center ...