React - Deployment - Routing for client side router

About

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

Solutions

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:

<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'));
 });
{
    "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" }
    ]
}

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

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]

Documentation / Reference





Discover More
React - Deploy

in React Context See React Native Starter Project...
React - Hosting

Because a react application is a client application, you can host your website in any static web hosting offering. If you plan to use server side rendering, you would need to have an extra node server....



Share this page:
Follow us:
Task Runner