Hide JSS Rendering with invalid datasource

On a recent JSS project, we came across a scenario where the client had inadvertently configured a datasource on a rendering. This was done either by manually changing the path to the datasource in the rendering or by deleting the datasource item altogether. After publishing, the result was that the rendering was showing in the live page (in the development environment) but with no data. It was essentially blank.

Let’s look at the layout service result for scenarios where the data source is filled in correctly and when it’s not.

#1 shows that data that is filled in correctly. You can see all the field objects listed there with their value properties. In #2, the fields object has no field object children. It just has the children[] (which we added to the layout service) and the cache time field.

Also note in #3 the odd difference in datasource format as #3 has it in a guid format and #2 does not, but that is actually unrelated to whether or not the datasource is invalid. The arrow points to the corresponding datasource field on the invalid datasource Json.

One Possible Solve

A simple solve for this could look like this:

let titleField = JSON.parse(JSON.stringify(title));
if(titleField.props?.field==null){
return <>;

This simply tests to see if one of the expected fields is in the “fields” collection. Even if the content author leaves the field blank, the field will still be there with a “value” of null. If it’s not there, you know the datasource is not set.

A Better Solve

A better solve for this would be to determine if the datasource was actually valid in a context resolver.

public class ItemContentsResolver : RenderingContentsResolver
    {
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            Assert.ArgumentNotNull(rendering, nameof(rendering));
            Assert.ArgumentNotNull(renderingConfig, nameof(renderingConfig));

            var result = new JObject()
            {
                ["IsValidDatasource"] = false
            };

            Item dataSourceItem = Sitecore.Context.Database.GetItem(rendering.DataSource);
            result["IsValidDatasource"] = dataSourceItem != null ? true : false;
            return result;
         }
     }

This essentially means you can write a function that every rendering can use to determine if it’s datasource is valid just by looking at this field. The rendering can then act appropriately based on that information.

About Phil Paris

Hi, my name is Phil Paris and I’m a Sitecore Architect and general Sitecore enthusiast. I’ve been working with Sitecore since 2013. Through this blog I will be sharing Sitecore insights, tips and tricks, best practices and general knowledge with the hopes to further the community at large. Please feel free to reach out to me at any time!

View all posts by Phil Paris →