React - Deployment - Routing for client side router

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

With client side router, a direct HTTP call will failed if you are not using some routing features (such as URL - URL Rewrite)

Advertising

3 - Solutions

3.1 - create-react-app

For a create-react-app React application, all URL must be redirected to the index.html page.

Example for a deployment with the following server:

.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    Options -MultiViews
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]
</IfModule>
app.use(express.static(path.join(__dirname, 'build')));
 
app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });
now.json
{
    "version": 2,
    "name": "my-react-app",
    "builds": [
        { "src": "package.json", "use": "@now/static-build", "config": { "distDir": "build" } }
    ],
    "routes": [
      { "src": "/static/(.*)", "headers": { "cache-control": "s-maxage=31536000,immutable" }, "dest": "/static/$1" },
      { "src": "/favicon.ico", "dest": "/favicon.ico" },
      { "src": "/asset-manifest.json", "dest": "/asset-manifest.json" },
      { "src": "/manifest.json", "dest": "/manifest.json" },
      { "src": "/precache-manifest.(.*)", "dest": "/precache-manifest.$1" },
      { "src": "/service-worker.js", "headers": { "cache-control": "s-maxage=0" }, "dest": "/service-worker.js" },
      { "src": "/(.*)", "headers": {"cache-control": "s-maxage=0"}, "dest": "/index.html" }
    ]
}

3.2 - React-snapshot

With React - React-Snapshot creating pre-rendered pages, example of htaccess to use for an Apache deployment after a build with react-snapshot

.htaccess
Options -MultiViews
RewriteEngine On
RewriteBase /
 
# Redirection to the HTML page
RewriteCond "$1.html" -f
RewriteCond "$1" !-f
RewriteRule "^(.*)$" "$1.html"
 
# Last one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

4 - Documentation / Reference

Advertising
web/javascript/react/deploy_routing.txt · Last modified: 2019/06/21 14:40 by gerardnico