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:
- Express works fine when running the project locally.
- 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.