I created a ReactJS application using Create-React-App, and wanted to deploy it on a Linux server. I followed a tutorial that showed how to do so very simply by installing pm2 and serve, then after running the command:
npm run build
I ran the command that actually hosted the application:
pm2 serve build
Now the problem is whenever I visit a url that is not the base one, or click reload from browser while I'm on a page other than home page, I get 404 not found error.
I understand the previous command is meant to serve a single page only. My question is: is there a way to make the url for example http://myserver:port/a go to Route a in my app? Or at least go to http://myserver:port/ ?
I already have Nginx installed on the same server, as I am using it to host a Flask Python app, but I'm very new to all this and I am looking for a simple way that works, as I faced some difficulties to get the Python app hosted.
Please note that I am only using React, no Redux, express, or any Database, if that is of any relevance. I am also using BrowserRouter inside my app.
pm2 serve
has a Single-Page-Application Mode (https://pm2.keymetrics.io/docs/usage/expose/#serving-spa-redirect-all-to-indexhtml)
From the docs:
To automatically redirect all queries to the index.html use the --spa option:
pm2 serve build --spa
Or if using ecosystem.config.js
file:
module.exports = {
script: "serve",
env: {
PM2_SERVE_PATH: 'build',
PM2_SERVE_PORT: 8080,
PM2_SERVE_SPA: 'true',
PM2_SERVE_HOMEPAGE: '/index.html'
}
}