Skip to content

Instantly share code, notes, and snippets.

@Mwamitovi
Created August 6, 2020 14:25
Show Gist options
  • Save Mwamitovi/c83379367d3221fd782138ebc1adfe96 to your computer and use it in GitHub Desktop.
Save Mwamitovi/c83379367d3221fd782138ebc1adfe96 to your computer and use it in GitHub Desktop.
Serve a react project on Heroku
// Step-1:
// create a script server file at the project root e.g. server.js
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const publicPath = path.join(__dirname, 'build');
// serve the build folder
app.use(express.static(publicPath));
// In case, user requests a resource not in build/, ensure that index.html is served
app.get('*', (req, res, next) => {
if (
req.headers['x-forward-proto'] !== 'https' &&
process.env.NODE_ENV === 'production'
) {
res.redirect('https://' + req.headers.host + req.url);
res.sendFile(path.join(publicPath, 'index.html'));
} else {
next();
}
});
// start the server on given port (local env: port 3000)
app.listen(port, () => {
console.log(`Server is up on port ${port}!`);
});
// Step-2:
// Add this to your package.json (guides in reading file path)
{
//...
"homepage": ".",
// ...
}
// Step-3:
// As you push a react project to heroku, the build process is always run.
// You will need to configure a node script to guide Heroku
// Thus you need a Procfile (within the project root)
// remember to replace "server.js" with the actual server script that you created in step-1
web: node server.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment