react-rails: Server-side rendering is not working with sprockets-rails 3.0

In sprockets-rails 3.0 Rails.application.assets is disabled when config.assets.compile=false (https://github.com/rails/sprockets-rails/pull/220). And React::ServerRendering::SprocketsRenderer is failing on production environment at this line, with undefined method '[]' for nil:NilClass

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 53 (19 by maintainers)

Commits related to this issue

Most upvoted comments

I can confirm that I only had to add Rails.application.config.assets.precompile += %w( react-server.js components.js ) in config/initalizers/assets.rb to get server side rendering work on Heroku.

Ohh strange. When it creates the manifest, the manifest has production/react-server instead of react-server. Then, SprocketsRenderer fails to find react-server since it has a different logical path.

I found a workaround:

  1. Add a JS file, server_rendering.js

  2. Make sure server_rendering.js is compiled (Rails.application.config.assets.precompile += %w( server_rendering.js ))

  3. Add to server_rendering.js:

    //= require react-server 
    //= require components
    // Require everything needed for server rendering 
    
  4. Specify only server_rendering.js for server rendering:

      config.react.server_renderer_options = {
        files: ["server_rendering.js"], # files to load for prerendering
      }
    

This way, it bundles react-server into server_rendering.js, it doesn’t look it up when you try to render a page!

I’ll look for a proper fix tonight or tomorrow!