Search code examples
node.jsreactjsreact-routercreate-react-appserver-side-rendering

Server-side rendering with React Router "Browser history needs a DOM"


I've scanned through the internet for two days but I can't get the gist of implementing SSR with react-routes. It took me 5 days to somehow understand all this without the routes. But now I'm unable to understand further with using react-routes. Here's the necessary details-

server/server.js

import express from 'express';
import fs from 'fs';
import path from 'path';

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';

import App from '../src/App';

const PORT = process.env.PORT || 8080;

const app = express();

app.use(express.static(path.resolve('./build')))

app.get('*', (req, res) => {

    fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {

    if (err) {
      console.log(err);
      return res.status(500).send('Some error happened');
        }

        const context = {};
        const app = ReactDOMServer.renderToString(
            <StaticRouter location={req.url} context={context}>
                <App />
            </StaticRouter>
        )
        
    return res.send(
      data.replace(
        '<div id="root"></div>',
        `<div id="root">${app}</div>`
      )
    );
    });
    
});

app.listen(PORT, () => {
  console.log(`App launched on ${PORT}`);
});

server/index.js

require('ignore-styles')

require('@babel/register')({
    ignore: [/(node_module)/],
    presets: ['@babel/preset-env', '@babel/preset-react']
})

require('./server')

src/App.js

import React from "react";
import {BrowserRouter, Switch, Route, Link} from 'react-router-dom';
import "./App.css";

function App() {

  return (
    <BrowserRouter>
      <Switch>
        <Route path='/' exact component={() => <Link to='/about'>This is Home. Go to About.</Link>} />
        <Route path='/about' component={() => <Link to='/'>This is About. Go to Home.</Link>} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.hydrate(<App />, document.getElementById('root'));

serviceWorker.unregister();

Solution

  • Remove the BrowserRouter from the App and put it in your index file.

    index.js

    ReactDOM.hydrate(
           <BrowserRouter>
              <App />
           </BrowserRouter>, 
       document.getElementById('root')
    );
    

    App.js

    import React from "react";
    import { Switch, Route, Link} from 'react-router-dom';
    import "./App.css";
    
    function App() {
    
      return (
          <Switch>
            <Route path='/' exact component={() => <Link to='/about'>This is Home. Go to About.</Link>} />
            <Route path='/about' component={() => <Link to='/'>This is About. Go to Home.</Link>} />
          </Switch>
      );
    }
    

    Since <App /> contains BrowserRouter and you're using it in the server. BrowserRouter cannot be processed in the server since it requires DOM.

    Also, import your StaticRouter from react-router not react-router-dom.

    You could check the docs here

    import { StaticRouter } from 'react-router';