Add data to server-side rendering view bag

Version: 22.x

When running a JSS app in integrated mode, such as when server-side rendering the JSS app using the Sitecore-managed Node.js rendering engine, the rendering engine invokes a renderView function exposed by the server bundle of the JSS application.

The function signature is:

RequestResponse
export const renderView = (callback, path, data, viewBag) => { ... }

The primary model/data passed into the function in the data argument is the output of the Sitecore Layout Service, containing route and context data. This allows the app to initialize and render without a REST call, allowing for server-side rendering.

If your application requires additional data for server-side rendering, you can populate the viewBag argument of the function with additional data with the help of the getRenderingEngineViewBag pipeline. By default, JSS includes the language of the rendered item as viewBag.language and the translation dictionary for the application as viewBag.dictionary to facilitate the server-side rendering of dictionary items.

To add more data to the viewBag argument, you must extend the getRenderingEngineViewBag pipeline.

To add more data to the viewBag argument:

  1. In your Sitecore solution, create a new processor. For example:

    RequestResponse
    public class AddExampleData : IGetRenderingEngineViewBagProcessor
    {
        public void Process(GetRenderingEngineViewBagArgs args)
        {
            // would be accessible in renderView as viewBag.hello
            args.ViewBag.hello = "world";
        }
    }
    
  2. Instruct Sitecore to use the custom processor AddExampleData instead of the default processor for the getRenderingEngineViewBag pipeline. Create a configuration patch, for example App_Config/Include/CustomViewBagPipeline.config and add the following configuration:

    RequestResponse
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
      <sitecore>
        <pipelines>
          <group groupName="javaScriptServices">
            <pipelines>
              <getRenderingEngineViewBag>
                <processor type="SitecoreJss.Examples.AddExampleData, SitecoreJss.Examples" />
              </getRenderingEngineViewBag>
            </pipelines>
          </group>
        </pipelines>
      </sitecore>
    </configuration>
    
  3. In your JSS application, you can now operate on your additional data. For example:

    Note

    The data contained in the arguments data and viewBag is a JSON string to control the JSON serialization process.

    RequestResponse
    const renderView = (callback, path, data, viewBag) => {
      data = JSON.parse(data);
      viewBag = JSON.parse(viewBag);
    
      //console output server-side will be routed to Sitecore logs
      console.log(`Hello ${viewBag.hello}`);
    
      // ...
    }
    

Do you have some feedback for us?

If you have suggestions for improving this article,