I've deployed my MERN app on Heroku and everything was fine until I realized an issue every time I refresh the page or try to access a route from the address bar. While navigation through React Router links is fine, trying to go directly to a route from URL address bar or refreshing the page is causing the app to break and sending server responses directly to the browser instead of rendering the component - to clarify: if a given route was supposed to make a GET request and display some data, the actual JSON is displayed on-screen.
As far as I've checked, this is happening only on components that make a GET request.
server.js
// INITIATE APP
const app = express();
// MIDDLEWARE
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use(passport.initialize());
const isProduction = process.env.NODE_ENV === "production";
// Priority serve any static files
isProduction &&
app.use(express.static(path.resolve(__dirname, "../client/build")));
// CONNECT TO DATABASE
// db config
const dbConnection = isProduction
? process.env.MONGO_URI_PROD
: process.env.MONGO_URI_DEV;
mongoose.connect(dbConnection, () => {
console.log("Successfully connected to database");
});
// ROUTES
const authRouter = require("./routes/auth");
const detailsRouter = require("./routes/details");
const diaryRouter = require("./routes/diary");
const resultsRouter = require("./routes/results");
const settingsRouter = require("./routes/settings");
app.use("/auth", authRouter);
app.use("/details", detailsRouter);
app.use("/diary", diaryRouter);
app.use("/results", resultsRouter);
app.use("/settings", settingsRouter);
// All remaining requests return the React app, so it can handle routing
isProduction &&
app.get("*", function (request, response) {
response.sendFile(path.resolve(__dirname, "../client/build", "index.html"));
});
// DEFINE PORTS
const port = process.env.PORT || 5000;
// START SERVER
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
By the end of the code above, right before Define ports, there is this statement that I included to fix a similar issue happening on other routes too. I thought this was going to prevent this error in any situation, but it seems that this isn't the case. You can try the app here (you can delete the account on /settings after testing).