Add data to server-side rendering view bag
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:
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:
-
In your Sitecore solution, create a new processor. For example:
RequestResponsepublic class AddExampleData : IGetRenderingEngineViewBagProcessor { public void Process(GetRenderingEngineViewBagArgs args) { // would be accessible in renderView as viewBag.hello args.ViewBag.hello = "world"; } } -
Instruct Sitecore to use the custom processor
AddExampleDatainstead of the default processor for thegetRenderingEngineViewBagpipeline. Create a configuration patch, for exampleApp_Config/Include/CustomViewBagPipeline.configand 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> -
In your JSS application, you can now operate on your additional data. For example:
NoteThe data contained in the arguments
dataandviewBagis a JSON string to control the JSON serialization process.RequestResponseconst 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}`); // ... }