Search code examples
reactjsreduxcreate-react-appredux-sagaserver-side-rendering

SSR with React.js (create-react-app, react-router v4, redux and sagas)


I successfully configured client and server. I can generate html with preloaded data but I have a problem with general concept. At this point I need to find a way to call server to do the job when user goes to some route. When and how I should do that? Inside componentWillMount ? Component: <Route path="/wall" component={Wall}/>

class Wall extends Component {
  componentWillMount(){
   if (csr){
    const { pathname, search } = this.props.location;
    //to use Promise? something like that? it should trigger server to prepare html
    return fetch(`'${servername}/${pathname}${search}'`);        
   } 
   if (ssr){
    {{fetch data and prepare index.html}}
   }
  }
  componentDidUpdate(prevProps, prevState) {
     {{code}}
  }
  render() {
    return (...)
  }
  ...

General idea: user goes to /wall => client sends request to server to render it => server renders it and puts html into index.html => server responds to client with status 200 => client shows the page => updates are handled by client
I might be wrong. Please correct me if I am. I will be grateful for any help or any other solution.

Edit: I want to use SSR only for first load. Later CSR would take care of rest.


Solution

  • You will need a custom function which fetches the data and returns a promise so that you can start the rendering after the data fetching is done and then send the rendered HTML to the client. Here is a basic idea for that

    But usually building a custom solution for SSR react app can be quite painful. I would suggest using NextJS (I am using it. It's awesome) or AfterJS.

    Unfortunately, NextJS doesn't support React Router 4. It has it's own routing mechanism which works fine. But if you are a fan of react router 4 or the ideology of react router 4, you can go for AfterJS