Steps for relocating Express server (using MERN stack) to a subdirectory and functioning on Heroku

In my MERN stack project, I recently had to reorganize the server-related files into their own subdirectory due to issues with ESLINT, VSCODE, and package.json configurations that were causing errors.

However, after making this change, Heroku started throwing errors related to Express not being able to serve the files. You can refer to the error screenshots in the Heroku log below.

The deployment on Heroku is successful without any build errors.

https://i.sstatic.net/2jDB0.png

This is how Express is configured in my server.js file:

// prod only, uses /public in dev env
app.use(express.static('index.html', { root: '../client/build' }) );

app.get('*', (req, res) => {
    res.sendFile(`index.html`, { root: '../client/build' });
});

Here's the directory structure of my project:

client/
   src/
   public/
   build/
   package.json
server/
   routes/
   models/
   server.js
   package.json
.gitignore
README.md
package.json // very small file only including scripts to satisfy Heroku

Contents of the root level package.json file:

{
"scripts": {
    "start": "cd server && node server.js",
    "build": "cd client && npm run build",
    "install-server": "cd server && npm install",
    "install-client": "cd client && npm install",
    "heroku-postbuild": "npm run install-server && npm run install-client && npm run build"
    }
}

Some additional notes:

  1. Express works fine when running the project locally.
  2. Heroku requires a package.json file at the root directory for Node.js projects, hence the small package.json file present there with minimal content.

Answer №1

After some troubleshooting, I found that switching from:

app.use(express.static('index.html', { root: '../client/build' }) );

To the following code:

app.use(express.static('/app/client/build'))

Resolved the issue I was facing.

I also attempted

app.use(express.static('index.html', { root: '/app/client/build' }) );
but it caused further issues with the website.

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

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

Tips for sending an array of data from the client to req.body in an axios request

I am facing an issue with sending user data collected from the front end via an ajax call to an axios post request in the back end. The parameters I need to pass include arrays of data, but when I check the req.body in the backend using console.log(), I no ...

Viewing the XML response generated by a JavaScript file (SOAP Request) on the IIS server

My current setup involves utilizing a calendar system with an API accessible via SOAP requests on an IIS server. Initially, my approach was to create an HTML page and use JavaScript to display the SOAP request response. However, the response did not retur ...

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

How can I make a POST request from one Express.js server to another Express.js server?

I am encountering an issue while trying to send a POST request from an ExpressJS server running on port 3000 to another server running on port 4000. Here is the code snippet I used: var post_options = { url: "http://172.28.49.9:4000/quizResponse", ti ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

Use JavaScript to limit Google Analytics and Yandex.Metrica to track only the referral sources and screen sizes

I prefer not to include external JavaScript on my website for unnecessary tracking purposes. However, I do need to gather referrer and screen size information, which cannot be achieved with a regular HTML img tag alone. What is the most standard-complian ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

Learning the process of connecting functions to events

// param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} } CustomButton = function(parameters) { var buttonElement = document.getElementById(parameters.id); // how c ...

Printing reports in Angular 9

I have a requirement in my Angular 9 application to generate and print reports. 1. I am looking for suggestions on how to handle printing reports where a user triggers the action by clicking a button, and the report data needs to be fetched from the datab ...

Issue: Module './utils/logger' not found

While running my node.js application, I encountered the following error message: [nodemon] 2.0.14 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node app.js` inter ...

Creating a hover effect for a specific card while maintaining the rest of the cards unaffected

When hovering over a card, all icons are displayed instead of just the icons for that specific card. I want to show only the icons for the card being hovered on (example output: image). The cards are generated automatically using v-for and fetching data fr ...

"Combining multiple DIVs into a single DIV with jQuery - a step-by-step guide

I have multiple DIVs with the same class, and I am looking to group them into a single DIV using either jQuery or pure JS. <div class="a"> <div>1</div> </div> <div class="a"> <div>2</div> ...

Transferring the chosen dropdown value to the following page

I am attempting to transfer the currently selected value from a dropdown to the next page using an HTTP request, so that the selected value is included in the URL of the subsequent page. The form dropdown element appears as follows: <form name="sortby ...

Creating an infinite loop using Jquery's append and setTimeout functions

I'm having trouble displaying my JSON data in a table and refreshing it periodically to check for new entries. Unfortunately, I seem to have gotten stuck in an infinite loop where the setTimeOut function keeps adding old entries. Can anyone help me tr ...

What could be the reason behind my Heroku app suddenly crashing without any visible errors?

After successfully starting the Nest application, about 50 seconds later it transitions from 'starting' to 'crashed'. The last log entry before the crash is a console log indicating the port number. View Heroku logs after successful bui ...

Strategies for concealing and revealing content within dynamically loaded AJAX data

I am attempting to show and hide data that is loaded using Ajax. $.ajax({ type: "POST", url: "/swip.php", data: {pid:sldnxtpst,sldnu:sldnu}, success: function(result) { $('.swip').prepend(result); } }); This data gets ...

Extracting IDs, classes, and elements from a DOM node and converting it into a string format

Can someone please guide me on how to extract the DOM tree string from an element? Let's consider this HTML structure: <div> <ul id="unordered"> <li class="list item">Some Content</li> </u ...

What is the process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

Why doesn't Material-UI seem to understand the theme.spacing function?

Issue with Material-UI's theme.spacing function I've encountered a problem while using Material-UI's theme.spacing function in a React application. It seems that the spacing function is not being recognized. The Javascript error message st ...