Background
As you may or may not know React often uses routing through the browser history API
A few of the common libraries that you might encounter would be:
- React Router DOM: https://www.npmjs.com/package/react-router-dom
- Wouter: https://www.npmjs.com/package/wouter (personal favorite)
These libraries will let you define routes and which components are being rendered.
Quick Example:
<Route path="/about"><AboutPage/></Route>
<Route path="/user/:id">
{params => <UserPage id={params.id} />}
</Route>
Running this in dev mode will work fine.
Issue
If you build the react app and try to host it with express you'll notice we run in an issue:
import * as express from 'express'
const app = express()
app.use(express.static(configuration.buildDirectory));
app.listen(8080, () => {
console.log(`Server started on port 8080`);
});
If you navigate to http://127.0.0.1:8080 you'll see your react app.
However if you navigate to http://127.0.0.1:8080/about
You will receive an error:
Can't GET /about
Solving the Issue
Our issue comes from the fact that express will only allow the route '/' to be used.
The idea is that we want to preserve the routes but still display our built index.html
For this we can add the following statement:
app.all('*', (req, res) => {
res.sendFile(path.join(configuration.buildDirectory, '/index.html'), (err) => {
if (err) {
res.status(500).send(err)
}
})
});
This means that for every route we will render the index.html
however since we are not redirecting we will preserve the URL scheme.
Pixium Digital - Shaping your project with technology and innovation
https://pixiumdigital.com
https://github.com/pixiumdigital
Top comments (0)