Module: ReactOnRailsPro::ServerRenderingJsCode

Defined in:
lib/react_on_rails_pro/server_rendering_js_code.rb

Constant Summary collapse

PLAIN_STREAMING_RENDER_FUNCTION_NAME =
"ReactOnRails.isServerStreamingSupported() ? " \
"'streamServerRenderedReactComponent' : 'serverRenderReactComponent'"

Class Method Summary collapse

Class Method Details

.async_props_setup_js(render_options) ⇒ String

Generates JavaScript code for async props setup when incremental rendering is enabled.

This code runs DURING the initial render request, BEFORE the component renders. It sets up the infrastructure that allows:

  1. Component to call getReactOnRailsAsyncProp("propName") → returns a Promise
  2. Update chunks to call asyncPropsManager.setProp("propName", value) → resolves the Promise

WHY isRSCBundle CHECK?

  • Async props only work with React Server Components (RSC)
  • RSC bundle has addAsyncPropsCapabilityToComponentProps method
  • Server bundle (non-RSC) doesn't support this pattern

RACE CONDITION HANDLING:

  • Uses getOrCreateAsyncPropsManager internally for lazy initialization
  • If initial render runs first: creates manager, stores in sharedExecutionContext
  • If update chunk arrives first: creates manager via getOrCreateAsyncPropsManager
  • Both share the same manager via sharedExecutionContext

WHY sharedExecutionContext?

  • The asyncPropManager needs to be accessible by update chunks that arrive later
  • Update chunks run in the same ExecutionContext, so they can retrieve it
  • sharedExecutionContext is NOT global - it's scoped to this HTTP request

Parameters:

  • render_options (Object)

    Options that control the rendering behavior

Returns:

  • (String)

    JavaScript code that sets up AsyncPropsManager or empty string



94
95
96
97
98
99
100
101
102
103
# File 'lib/react_on_rails_pro/server_rendering_js_code.rb', line 94

def async_props_setup_js(render_options)
  return "" unless render_options.internal_option(:async_props_block)

  <<-JS
    if (ReactOnRails.isRSCBundle) {
      var { props: propsWithAsyncProps } = ReactOnRails.addAsyncPropsCapabilityToComponentProps(usedProps, sharedExecutionContext);
      usedProps = propsWithAsyncProps;
    }
  JS
end

.generate_rsc_payload_js_function(render_options) ⇒ String

Generates the JavaScript function used for React Server Components payload generation Returns the JavaScript code that defines the generateRSCPayload function. It also adds necessary information to the railsContext to generate the RSC payload for any component in the app.

Returns:

  • (String)

    JavaScript code for RSC payload generation



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/react_on_rails_pro/server_rendering_js_code.rb', line 31

def generate_rsc_payload_js_function(render_options)
  return "" unless ReactOnRailsPro.configuration.enable_rsc_support && render_options.streaming?

  if render_options.rsc_payload_streaming?
    # When already on RSC bundle, we prevent further RSC payload generation
    # by throwing an error if generateRSCPayload is called
    return <<-JS
      if (typeof generateRSCPayload !== 'function') {
        globalThis.generateRSCPayload = function generateRSCPayload() {
          throw new Error('The rendering request is already running on the RSC bundle. Please ensure that generateRSCPayload is only called from any React Server Component.')
        }
      }
    JS
  end

  # To minimize the size of the HTTP request body sent to the node renderer,
  # we reuse the existing rendering request string within the generateRSCPayload function.
  # This approach allows us to simply replace the component name and props,
  # rather than rewriting the entire rendering request.
  # This regex finds the empty function call pattern `()` and replaces it with the component and props
  <<-JS
  railsContext.serverSideRSCPayloadParameters = {
    renderingRequest,
    rscBundleHash: #{ReactOnRailsPro::Utils.rsc_bundle_hash.to_json},
  }
  const runOnOtherBundle = globalThis.runOnOtherBundle;
  const generateRSCPayload = function generateRSCPayload(componentName, props, railsContext) {
    const { renderingRequest, rscBundleHash } = railsContext.serverSideRSCPayloadParameters;
    const propsString = JSON.stringify(props);
    const newRenderingRequest = renderingRequest.replace(
      /\\(\\s*\\)\\s*$/,
      function() { return `(${JSON.stringify(componentName)}, ${propsString})`; }
    );
    return runOnOtherBundle(rscBundleHash, newRenderingRequest);
  }
  JS
end

.render(props_string, rails_context, redux_stores, react_component_name, render_options) ⇒ String

Main rendering function that generates JavaScript code for server-side rendering

Parameters:

  • props_string (String)

    JSON string of props to pass to the React component

  • rails_context (String)

    JSON string of Rails context data

  • redux_stores (String)

    JavaScript code for Redux stores initialization

  • react_component_name (String)

    Name of the React component to render

  • render_options (Object)

    Options that control the rendering behavior

Returns:

  • (String)

    JavaScript code that will render the React component on the server



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/react_on_rails_pro/server_rendering_js_code.rb', line 112

def render(props_string, rails_context, redux_stores, react_component_name, render_options)
  rsc_support_enabled = ReactOnRailsPro.configuration.enable_rsc_support
  render_function_name =
    if rsc_support_enabled && render_options.streaming?
      # Select appropriate function based on whether the rendering request is running on server or rsc bundle
      # As the same rendering request is used to generate the rsc payload and SSR the component.
      "ReactOnRails.isRSCBundle ? 'serverRenderRSCReactComponent' : 'streamServerRenderedReactComponent'"
    elsif render_options.streaming?
      PLAIN_STREAMING_RENDER_FUNCTION_NAME
    else
      "'serverRenderReactComponent'"
    end
  streaming_params = if rsc_support_enabled && render_options.streaming?
                       config = ReactOnRailsPro.configuration
                       react_client_manifest_file = config.react_client_manifest_file
                       react_server_client_manifest_file = config.react_server_client_manifest_file
                       <<-JS
                          railsContext.reactClientManifestFileName = #{react_client_manifest_file.to_json};
                          railsContext.reactServerClientManifestFileName = #{react_server_client_manifest_file.to_json};
                       JS
                     elsif render_options.streaming?
                       # These keys are part of the streaming renderer contract, but non-RSC builds do not
                       # produce RSC manifests. Empty names avoid a failed filesystem lookup on the shell path.
                       <<-JS
                          railsContext.reactClientManifestFileName = "";
                          railsContext.reactServerClientManifestFileName = "";
                       JS
                     else
                       ""
                     end

  # This function is called with specific componentName and props when generateRSCPayload is invoked
  # In that case, it replaces the empty () with ('componentName', props) in the rendering request
  <<-JS
  (function(componentName = #{react_component_name.to_json}, props = undefined) {
    var railsContext = #{rails_context};
    #{streaming_params}
    #{generate_rsc_payload_js_function(render_options)}
    #{ssr_pre_hook_js}
    #{redux_stores}
    var usedProps = typeof props === 'undefined' ? #{props_string} : props;
    #{async_props_setup_js(render_options)}
    return ReactOnRails[#{render_function_name}]({
      name: componentName,
      domNodeId: #{render_options.dom_id.to_json},
      props: usedProps,
      trace: #{render_options.trace},
      railsContext: railsContext,
      throwJsErrors: #{ReactOnRailsPro.configuration.throw_js_errors},
      renderingReturnsPromises: #{ReactOnRailsPro.configuration.rendering_returns_promises},
      generateRSCPayload: typeof generateRSCPayload !== 'undefined' ? generateRSCPayload : undefined,
    });
  })()
  JS
end

.ssr_pre_hook_jsObject



23
24
25
# File 'lib/react_on_rails_pro/server_rendering_js_code.rb', line 23

def ssr_pre_hook_js
  ReactOnRailsPro.configuration.ssr_pre_hook_js || ""
end