react-router 4 – Browser history needs a DOM

You need to use different history provider for server side rendering because you don’t have a real DOM (and browser’s history) on server. So replacing BrowserRouter with Router and an alternate history provider in your app.js can resolve the issue. Also you don’t have to use two wrappers. You are using BrowserRouter twice, in app.js as well as clientIndex.js which is unnecessary.

import { Route, Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';

const history = createMemoryHistory();

  <Router history={history}>
   <Route path="https://stackoverflow.com/" exact render={( props ) => ( <div>Helloworld</div> )} />
  </Router>

You can now replace StaticRouter with ConnectedRouter which can be used both in client and server. I use the following code to choose between history and export it to be used in ConnectedRouter’s history.

export default (url="https://stackoverflow.com/") => {
// Create a history depending on the environment
  const history = isServer
    ? createMemoryHistory({
        initialEntries: [url]
     })
   : createBrowserHistory();
}

Leave a Comment