Thursday, 16 December 2021

React Router and NodeJS


Hosting your React app is usually as simple as copying over the files to a "public" or "static" directory.
 
You could simply paste the files onto an IIS or Apache Server and this article could still help you if you are using sub directories. However, I have written this to tackle the situation where a pre-existing web application will host, in this scenario the host application is written in NodeJS. 

Generally, all you need to worry about is serving the "index.html" file that comes in the production build bundle at the right time, something like: 
router.get('/myroute'async (req, res) => {
return res.sendFile(path.join(__dirname + '/public/client/index.html'));
}

// later on make the public directory accessible
app.use('/public'express.static(__dirname + '/public'));

However, in this case I want to use React Router to navigate to sub pages. e.g. myroute/ home, myroute/user etc...

The way to do it is to use a wildcard off of your main route so that your React app will load on every child route of "myroute":
// this is required to support any client side routing written in react.
router.get('/myroute/*', (reqres=> { 
    res.sendFile(path.join(__dirname + '/public/client/index.html'));
});
On the React application side the "basename" property of the Router wrapper component (in React Router 5+) needs to be set. In my case I set "base" when in production mode to "/myroute". This will mean React router will look for "/myroute/new" to render the Start component rather than just "/new".
const base = process.env.NODE_ENV === "production" ? "/myroute" : "/";

<Router basename={base}>
   <Switch>
     <Route exact path='/new'>
       <Start />
     </Route>
   </Switch>
</Router>
It is also worth mentioning that it is considered best practice to add a href meta tag to you index.html page.

References
react-router | https://reactrouter.com/web
medium | https://dev-listener.medium.com/react-routes-nodejs-routes-2875f148065b

No comments:

Post a Comment