Skip to content

Front-end-as-a-Service (FEaaS) Support #11

Open

Description

@robearlam

What would you add to the SDK?

We need to decide the best approach to introduce Front-end-as-a-Service (FEaaS) support into the SDK.

JSS leverages a React library called @sitecore-feaas/clientside/react. We need to decide whether to leverage the same library ourselves directly in the front-end or if we want to introduce our own middleware that has the same functionality included?

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. added
    enhancement
    on Aug 21, 2024
  2. added this to the V1 Release milestone on Dec 13, 2024
  3. jballe commented on Oct 11, 2025

    @jballe
    Contributor

    From my point of view, it is completely fine that the components are rendered clientside.

    We have an initial version running, but there are some dependencies to how we are creating our frontend bundles and it we had to do a few weird serialization handling that is at least not the most pretty code I have written 😄

    Component model to get values from layout response:

    public class FEaaSComponentModel : BaseComponentModel
    {
        [SitecoreComponentParameter]
        public string? RenderingIdentifier { get; set; }
    
        [SitecoreComponentParameter]
        public string? LibraryId { get; set; }
    
        [SitecoreComponentParameter]
        public string? ComponentId { get; set; }
    
        [SitecoreComponentParameter]
        public string? ComponentVersion { get; set; } = "responsive";
    
        [SitecoreComponentParameter]
        public string? ComponentRevision { get; set; } = "published";
    
        [SitecoreComponentParameter]
        public string? ComponentInstanceId { get; set; }
    
        [SitecoreComponentParameter]
        public string? ComponentHostName { get; set; } = "https://feaas.blob.core.windows.net";
    
        public JsonDocument? DataSource { get; set; }
    }

    The View Component and deserialization

    [ViewComponent(Name = ViewComponentName)]
    public class FEaaSWrapperViewComponent(IViewModelBinder binder) : ViewComponent
    {
        // This rendering is part of Foundation/Headless Services, so we have to stick with the name
        public const string ViewComponentName = "FEaaSWrapper";
    
        private static readonly JsonSerializerOptions _options = CreateOptions();
    
        public async Task<IViewComponentResult> InvokeAsync(CancellationToken cancellationToken)
        {
            var renderingContext = HttpContext?.GetSitecoreRenderingContext();
            var model = await binder.Bind<FEaaSComponentModel>(ViewContext).ConfigureAwait(false);
    
            if (renderingContext?.Component?.Fields?.Count > 0)
            {
                var castedDictionary = renderingContext.Component.Fields.ToDictionary(x => x.Key, x => (JsonSerializedField)x.Value);
                var dataSource = await JsonSerializerWrapper.SerializeToStringAsync<IDictionary<string, JsonSerializedField>>(castedDictionary, _options, cancellationToken);
    
                model.DataSource = JsonDocument.Parse(dataSource);
            }
    
            return View(model);
        }
    
        private static JsonSerializerOptions CreateOptions()
        {
            var options = new JsonSerializerOptions
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            };
    
            options.Converters.Add(new SerializedJsonFieldConverter());
    
            return options;
        }
    
        public class SerializedJsonFieldConverter : JsonConverter<JsonSerializedField>
        {
            public override bool CanConvert(Type typeToConvert) => base.CanConvert(typeToConvert);
    
            public override JsonSerializedField? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
    
            public override void Write(Utf8JsonWriter writer, JsonSerializedField value, JsonSerializerOptions options) => writer.WriteRawValue(GetInnerValue(value.GetRawValue()));
    
            private string GetInnerValue(string json)
            {
                const string needle1 = "{\"value\":";
                const string needle2 = "}";
    
                if (string.IsNullOrWhiteSpace(json) || !json.StartsWith(needle1) || !json.EndsWith(needle2))
                {
                    return json;
                }
    
                return json.Substring(needle1.Length, json.Length - needle1.Length - needle2.Length);
            }
        }
    }

    Our view:

    @model FEaaSComponentModel
    @inject ClientSidePropsRenderer props
    
    <div class="component feeas @Model.Styles" id="@Model.RenderingIdentifier">
        <div class="component-content" app="feaas">
            @await props.RenderAsync(Model)
        </div>
    </div>

    We have an implementation to render the model as json in a specific script tag and some javascript to instantiate a React component with those data as props.
    We are lazy loading the bundle with the @sitecore-feaas/clientside bundle as it is quite significant so in our main bundle we have:

    elementExistFunction('[app="feaas"]', (elements) => import('./feaaswrapper').then(x => x.init(elements)));
    // feaaswrapper.ts
    
    import * as FEEAS from '@sitecore-feaas/clientside'
    import { getRenderedClientSideProps } from '@/utils/islands';
    
    
    export const init = function (elements: NodeListOf<Element>) {
        elements.forEach(initElm)
    }
    
    
    type FEaaSModel = {
        renderingIdentifier: string;
        libraryId: string;
        componentId: string;
        componentVersion: string;
        componentRevision: string;
        componentInstanceId: string;
        componentHostName: string;
        dataSource: object;
    };
    
    async function initElm(element: HTMLElement) {
        const props = getRenderedClientSideProps(element) as FEaaSModel;
        if (!props?.libraryId) {
            console.warn("Cannot render FEaaS component", element);
            return;
        }
    
        element.innerHTML = '';
        FEEAS.loadStylesheet(props.libraryId);
    
        const dataSettingsConfig = {};
        dataSettingsConfig[props.componentId] = {
            ...props.dataSource
        };
    
        const revisionNumber = parseInt(props.componentRevision);
        const revision = !isNaN(revisionNumber) ? revisionNumber : ["staged","published","saved"].indexOf(props.componentRevision) >= 0 ? props.componentRevision as "staged" | "published" | "saved" : undefined;
    
        const libraryProps: FEEAS.FEAASComponentProps = {
            hostname: props.componentHostName,
            library: props.libraryId,
            component: props.componentId,
            version: props.componentVersion,
            src: `${props.libraryId}/${props.componentId}`,
            revision,
            instance: props.componentInstanceId,
            data: props.dataSource ?? {},
        };
    
        FEEAS.renderComponentPromise(libraryProps, element);
    }

    The SDK and xm-starter doesn't have any way to handle client-side code, and I actually like that, but I guess we can barely achieve this without something. Maybe just an example or skeleton on how to activate it and some recommended markup.

    However, would this be enough to support XM Components? It seems to work, but it might be that there are functionality that we are not aware of (yet) that is missing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions