How to bundle a React app to a subdirectory on a server?

react router htaccess subdirectory
react-router basename
how to redirect in react js
react-router not working on server
how to deploy react app to apache server
react-router base url
create-react-app prefix
create react app subdomain

I have a React app I've been developing on my localhost. I want to copy it to a server into a subdirectory called vensa.

My webpack config file looks like this..

const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: 'build',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css!sass')
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css')
      },
      {
        test: /\.(png|eot|svg|ttf|woff(2)?)(\?v=\d+\.\d+\.\d+)?/,
        loader: 'url'
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('vensa-dashboard.css')
  ],
  devServer: {
    historyApiFallback: true,
    contentBase: './build'
  }
};

The index.html file looks like this...

<!DOCTYPE html>
<html>
<head>
  <title>Vensa Development Test</title>
  <link rel="stylesheet" href="/vensa-dashboard.css">
</head>
<body>
  <div class="container"></div>
  <script src="/bundle.js"></script>
</body>
</html>

and my routes.js file is...

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import VensaDashboard from './components/VensaDashboard';
import Inbox from './components/Inbox';
import Todo from './components/Todo';
import Home from './components/Home';

export default (
  <Route path="/" component={VensaDashboard}>
    <IndexRoute component={Home} />
    <Route path="/message" component={Inbox} />
    <Route path="/todo/:todoPage" component={Todo} />
  </Route>
);

However, if I do just run webpack -p and copy the 3 files over to that subdirectory, it doesn't work as the root path is / and it can't find the js and css files. I'm not sure what (the best way) to change in (probably one or all of these 3 files) to get it to work in a subdirectory?

The full source code of the app is here in case that helps.

Thanks!


If you are using React Router v4 you should be able to set it using basename={foobar}.

<Router history={browserHistory} basename={'foobar'}>
  <Route path="/" component={App} />
</Router>

Link to the docs: https://reacttraining.com/react-router/web/api/BrowserRouter

Note: if using create-react-app in a sub directory you will also want to set "homepage": "/foobar/", in your package.json file. So the production build points at the right path.

If you are using react-router-dom, If you know your directory name you could set basename to "/directory-name" in the router. or. If you want to  Note: if using create-react-app in a sub directory you will also want to set "homepage": "/foobar/", in your package.json file. So the production build points at the right path. So the production build points at the right path.


I had to do something similar recently in order to get a react app running in a sub directory. Try the below and see how you get on.

import React from 'react';
import { Router, Route, IndexRoute, useRouterHistory  } from 'react-router';
import { createHistory } from 'history';
import VensaDashboard from './components/VensaDashboard';
import Inbox from './components/Inbox';
import Todo from './components/Todo';
import Home from './components/Home';

// specify basename below if running in a subdirectory or set as "/" if app runs in root
const appHistory = useRouterHistory(createHistory)({
  basename: "/vensa"
});

export default (
  <Router history={appHistory} />
    <Route path="/" component={VensaDashboard}>
      <IndexRoute component={Home} />
      <Route path="/message" component={Inbox} />
      <Route path="/todo/:todoPage" component={Todo} />
    </Route>
  </Router>
);

You may also have to update the path to your bundle.js file in index.html as shown below

<!DOCTYPE html>
<html>
<head>
  <title>Vensa Development Test</title>
  <link rel="stylesheet" href="/vensa-dashboard.css">
</head>
<body>
  <div class="container"></div>
  <script src="bundle.js"></script>
</body>
</html>

Set the basename. Setting the basename attribute on the <Router /> component tells React Router that the app will be served from a subdirectory. Set the app homepage. Located in your package. Update the Routes. You can also use the value set in the homepage property discussed above in your JSX. Update the Links. So you have to access your reactjs website via this url. so you need to follow below steps during create build in your lolca machine or server. 1. Set the basename. Setting the basename attribute on the <Router /> component tells React Router that the app will be served from a subdirectory.


  1. Add "homepage": "https://yourdomain/subdirectory/" in package.json
  2. Update the Routes, set sub directory in route,
<Router basename={'/directory-name'}>
  <Route path='/' component={Home} />
</Router>
  1. Add base in public/index.html. It helps to set path without issues.

    <base href="%PUBLIC_URL%/">

  2. make all css, js, images & all resource loading './assets/your resource.'

  3. Only look if you are using history. add basename in history

    const historyConfig = {
        basename: 'your subdirectory'
    };
    const history = createBrowserHistory(historyConfig);

Let's start with an obvious statement: React application deployed to a subfolder will and assets from the root folder without accounting for a subdirectory. Works for local dev server (the app will be served from the root) and  An elegant solution of deploying React app into a subdirectory. Let's start with an obvious statement: React application deployed to a subfolder will not work out of the box: The reason for that is the path: React still tries to load its resources and assets from the root folder without accounting for a subdirectory.


Use the html-webpack-plugin to generate your final index.html with the correct bundle names automatically injected into it.

Then set output.publicPath in your webpack config to tell webpack the subdirectory your assets will be deployed to:

output: {
  path: 'build',
  publicPath: "/vensa/",
  filename: 'bundle.js'
},

How do you deploy a react app to a subdirectory? Setting the basename attribute on the <Router /> component tells React Router that the app will be served from a subdirectory.


Or you could use an environment variable to adjust all your links manually.

const ENV = process.env.NODE_ENV || 'local'; //development
const config = {
    publicPath: ENV !== 'production' ? '/' : '/dev/'
};
plugins: ([
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(ENV),
            'process.env.config': JSON.stringify(config)
        })
})

Then one of your routes:

<Route path={process.env.config.publicPath + "account/"} component={Account} />

Then your links:

<Link class="panel-close" href={process.env.config.publicPath + "account/"} >Account</Link>

This worked great for me. Especially since I'm using preact, whose preact-router doesn't really support the basename at this time.

<Router history={browserHistory} basename={'foobar'}>
  <Route path="/" component={App} />
</Router>

uses the Hash part of your URL to sync. May 2018 - Updated to match React Router v4 API. September 2019 - Updated to match React Router v5 API, added React Create App part. If you ever had to deploy React Router app to the subfolder on the server, you know what the problem is. Routes will get messed up once you upload it to the server. Here are two solutions I use in these cases.


I have a React app I've been developing on my localhost. I want to copy it to a server into a subdirectory called vensa. My webpack config file looks like this.. How to deploy a React application: An in-depth overview A lot of front end application development companies are using React for developing applications. Deploying an application refers to making the application accessible to the world through internet.


How should I configure create-react-app to serve app from subdirectory? - reactjs​. I have classic web application rendered on server. I want to create admin panel​  The use of process.env.REACT_APP_ meant that we could load in environment variables at build time. I encourage you to create new Firebase and Facebook applications for to utilize in your applications when not in development, but we’re not going to cover how to do that again.


Trying to deploy a react app to a domain's subfolder requires a bit of server { # SSL Config listen 443 ssl; listen [::]:443 ssl; server_name  Create React App . Create React App is a comfortable environment for learning React, and is the best way to start building a new single-page application in React. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.