Conditional Rendering On Server Side

I am using next.js for server side rendering and react.js for client side.

Want to do conditional rendering on the basis of window size in server side. Like for 200px width render A component and for 400px width render B component.

In server side, we have no access to the window object and we have no idea about the device our client is using. So AFAIK we cant do conditional rendering on server side.

I have thought of some solutions, but don't know is it possible or not -
1. Send the device info or window object as json with the http request.
2. Don't render the conditional components in server side and re-render (hydrate) them on client side.

But I don't know what is the best practice and what is more efficient than other. New suggestions are also welcome.



Consider using next approach:

  1. On server side you can predict device type by parsing user-agent with help of mobile-detect package and pass expected values to an isomorphic HOC created on top of react-sizes which allows to setup "predicted" screen sizes to work on server side.
  2. Wrap your conditional logic with appropriate to your business logic structures with adaptive HOC you've created
  3. ...
  4. Profit

Be aware of at least next cases you should take care of:

  1. Narrow screens of desktop user-agents will be rendered as for desktop, but might start re-rendering on client side, as MatchMedia gonna do its work on client
  2. Any caching layer should include parsed device type into cache key so you will not cache potentially broken layout.