<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marcin Krasowski on Medium]]></title>
        <description><![CDATA[Stories by Marcin Krasowski on Medium]]></description>
        <link>https://medium.com/@marcin_krasowski?source=rss-46bb1aceab1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LV2dutt_2Bfy0Zap_1RdfA.png</url>
            <title>Stories by Marcin Krasowski on Medium</title>
            <link>https://medium.com/@marcin_krasowski?source=rss-46bb1aceab1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:08:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcin_krasowski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Composable B2B portal: self-service, commerce and lessons learned]]></title>
            <link>https://blog.stackademic.com/composable-b2b-portal-self-service-commerce-and-lessons-learned-134c5338eea9?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/134c5338eea9</guid>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[b2b]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 15:06:05 GMT</pubDate>
            <atom:updated>2025-12-16T17:10:40.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Digital transformation in B2B rarely happens in a single big-bang release. Most organisations move step by step: first exposing existing data to customers, then digitising transactions, and only later bringing internal workflows and content into the same composable stack. This project followed exactly that path, turning a traditional sales and support model into a composable B2B portal over several stages.</p><p><a href="https://osadkowski.pl/">Osadkowski</a>, a leading Polish agricultural supplier, operates in a market where large, time-sensitive orders, advisory sales and legacy systems make this gradual approach almost necessary. The team set out to build a composable digital platform that would connect three key applications:</p><ul><li>a B2B self-service portal,</li><li>a B2B e-commerce storefront integrated with OroCommerce,</li><li>and a backoffice application for administrators and internal teams.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ACqv2UlPor8-RbYj.png" /></figure><p>From the beginning, the web applications were designed with future channels in mind. System’s architecture was shaped so that it could later support additional ways of accessing the platform — including mobile — without duplicating business logic or rebuilding the entire stack.</p><p>The project started before <a href="https://www.openselfservice.com/blog/how-composable-client-portal-for-orange-energia-became-foundation-for-open-self-service">our later work with Orange Energia</a>, and the cooperation with Osadkowski continues to this day. Many of the patterns tested here later influenced how we think about composable frontends and how we designed Open Self Service as an open-source framework for this kind of solution.</p><p>In the first part this article looks at the project as a whole: the business context, the architectural choices, the practical challenges and trade-offs we encountered, and the lessons that shaped later work — including <a href="https://www.openselfservice.com/">Open Self Service</a> (our open-source composable frontend framework for building large scale customer support portals and apps).</p><p>Second part is a more technical deep dive that revisits these challenges in detail and illustrate the concrete conclusions we drew from them. Not here for the business story? You can skip directly to the technical architecture overview.</p><h3>Why Osadkowski needed digital self-service and what the platform delivers</h3><p>Osadkowski has been active in the agricultural market since 1990, specializing in plant protection, seeds, crops and additives. It works closely with Polish farms, building its position on trust and expert advice. Long before the e-commerce journey started, customer conversations were already pointing towards a need for better self-service and customer support: a place where clients could see their data, documents and requests without calling or emailing every time.</p><p>At the same time, existing processes and systems were fragmented. ERP and CRM handled core operations, while a separate WordPress installation powered large chunks of marketing and knowledge content. Customers did not have a single, coherent place where they could browse products, handle everyday self-service tasks, interact with support and access expert knowledge.</p><p>The new digital platform responds to these needs in several ways:</p><ul><li><strong>Advanced product discovery</strong>: growers can filter and search assortments based on pest type, composition, soil requirements or grain category, not just by name or SKU.</li><li><strong>Transparent availability and delivery information</strong>: users see current availability and realistic delivery times, including options for next-day delivery where logistics allow it.</li><li><strong>Dynamic discount and loyalty program</strong>: order values are automatically recalculated based on current and historical purchases, rewarding long-term relationships rather than one-off transactions.</li><li><strong>Unified self-service and support flows</strong>: contracts, orders, documents and key requests are available in one place, so customers can resolve most tasks without contacting support.</li><li><strong>Financial and logistics self-service</strong>: online payments, order tracking and access to documents and invoices simplify work on the farm side.</li></ul><p>All of this is implemented on top of a MACH-aligned architecture: microservices, API-first integration, cloud-native infrastructure and headless frontend. The frontend is built with Next.js and a component library that makes it easier to evolve the UI without rewriting core flows.</p><h4>Business outcomes and ongoing evolution</h4><p>Results became visible quickly. Within less than nine months from the start of implementation, the new solution went live. After three months of operation it already <strong>served around 90,000 B2B users and saw nearly 130% traffic growth</strong> compared to the previous year, as <a href="https://hycom.digital/insights/osadkowski-digitalization">highlighted in the original Hycom case study</a> about Osadkowski’s digitalization.</p><p>Equally important, the new platform created a foundation for gradual transformation. Instead of a one-off launch, Osadkowski and Hycom have been iterating on the system in regular sprints, introducing new capabilities and optimizations while keeping the composable architecture intact.</p><h3>Technical architecture and lessons learned</h3><h4>Technical architecture overview</h4><p>Currently, on the technical side, the solution is built as a composable platform rather than a single monolith. The web frontends run on Next.js, behind them sits a backend-for-frontend (BFF) layer, and behind the BFF there is a landscape of several dozen microservices and external systems such as OroCommerce and ERP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zjd14qSzt_qHnGhK.png" /></figure><p>The platform evolved in stages.</p><p>First, the team built a B2B self-service portal that introduced digital self-service and customer support flows that previously did not exist. This became the starting point for Osadkowski’s broader transformation of customer experience and service operations.</p><p>Next came the commerce application, this time with a different approach to data modeling and BFF responsibilities. A backoffice application was added to support internal users.</p><p>In a later phase, marketing content and the knowledge base were migrated from WordPress into the new stack. This consolidated all customer-facing experiences on the composable platform.</p><p>The result is a set of focused applications that share the same foundation, which we will look at in more detail in the next section.</p><h4>Three bounded contexts on the same composable stack</h4><p>At its core, the solution consists of three bounded contexts that all follow the same composable shape: a React frontend, a backend-for-frontend (BFF) layer and a set of microservices and external systems behind it.</p><ul><li><strong>Self-service portal</strong> focuses on exposing existing data and processes from multiple backend systems (such as CRM, billing or contracts). Its BFF primarily aggregates responses from several services and exposes them through a single API, which keeps integrations manageable and helps avoid over-fetching on the frontend.</li><li><strong>B2B commerce storefront</strong> sits mainly on top of OroCommerce and Elasticsearch. Here the BFF acts as a domain layer: it normalizes API payloads into models for products, carts, orders and discounts, which later simplifies upgrades and multi-channel reuse.</li><li><strong>Backoffice app</strong> uses the same pattern for internal users. It orchestrates operational workflows and integrations, while Strapi remains the central place for content and navigation in the public-facing parts of the platform.</li></ul><p>These three contexts share infrastructure, deployment model and integration patterns, but differ in how much domain responsibility they place into the BFF — a difference that became important in later stages of the project.</p><h4>Backend-for-frontend patterns: how normalization paid off</h4><p>A key design decision in Osadkowski’s platform was how much responsibility to put into the BFF. In the first stage, the e-care BFF primarily aggregates responses from multiple backend systems and exposes them through a unified API. This aggregation-first approach simplifies integration with many backend services and reduces over-fetching on the frontend, but it also means that some domain complexity and mapping logic remain closer to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYpM0-1EbvBnMXW9zdihuQ.png" /></figure><p>As the commerce application was added, the team moved towards a stronger domain model in the BFF. Instead of only aggregating payloads from OroCommerce and other services, the commerce BFF <strong>normalizes them into stable, domain-oriented structures for products, carts, orders and discounts</strong>. This makes the frontend simpler, reduces coupling to any single e-commerce engine and makes it easier to reuse the same models across different channels, including the hybrid mobile app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37s4-OrB2mx2F6rwEEwapg.png" /></figure><p>The practical impact of this difference became clear during real work. When the team upgraded Strapi in the e-commerce area, most changes were limited to a few adjustments in the BFF layer, because the normalized models shielded the frontend from low-level API details. In the earlier e-care implementation, a similar upgrade would have required touching many places in the frontend that were still directly aware of backend shapes.</p><p>The contrast between these two approaches became an important lesson for later projects: thin, aggregating BFFs are a good fit for early stages, but long-lived platforms and multi-channel frontends benefit from a BFF that acts as a reusable domain layer. The same principle underlies how BFFs are designed in Open Self Service.</p><h4>Shared component library and frontend reuse</h4><p>From the beginning, the team wanted to reuse UI components between the self-service portal, commerce and other frontends. To achieve this, they introduced a shared component library, originally managed with <a href="https://bit.dev/">Bit</a> in an open-source setup. The idea was straightforward: versioned components, shared across applications, with a path towards a consistent design system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qdksxSHRgAzSHPgA.png" /></figure><p>In practice, this approach delivered clear benefits. Common building blocks for layout, navigation and domain-specific widgets could be implemented once and then consumed by multiple applications. Changes in shared components propagated in a controlled way thanks to explicit versioning, which is especially valuable in long-running projects with several frontends.</p><p>At the same time, running Bit in a self-hosted setup introduced notable friction. Bit is a powerful tool for sharing and versioning components across many applications, and in cloud-hosted scenarios it can be a good fit. In our case, however, the self-managed installation was relatively heavy: builds were slower and less predictable, and keeping the whole pipeline stable required more engineering effort than expected. It also added another tool that developers had to learn and operate, raising the onboarding threshold compared to plain npm packages. In later projects — including Open Self Service — these experiences pushed us towards simpler monorepo patterns, where classic npm packages and a standard toolchain provide similar reuse and versioning benefits with a lower operational cost.</p><h4>From WordPress to Strapi: unifying content and experience</h4><p>When the project started, Osadkowski already had a significant amount of marketing and knowledge content implemented on WordPress. That content played an important role in customer education and in supporting sales teams.</p><p>As the new composable platform took shape, maintaining a separate WordPress site for extensive content became a limitation:</p><ul><li>the user experience was fragmented between the new portal and the old content site,</li><li>maintaining consistent navigation and design across systems was harder,</li><li>some content could not be easily reused where it was needed most in the self-service and e-commerce flows.</li></ul><p>The team decided to migrate this content into the new stack and manage it through Strapi CMS. Strapi became responsible for:</p><ul><li>structured pages such as the “Knowledge” section,</li><li>expert articles and educational materials,</li><li>navigation elements that connect content with self-service and commerce journeys.</li></ul><p>Strapi’s role goes beyond storing articles. It gives marketing and product teams a way to manage rich content, educational materials and parts of the frontend structure in one place. This makes it easier to run campaigns, introduce new sections and maintain a consistent experience across content and transactional parts of the portal, without requiring code changes for every adjustment. The same philosophy of CMS-driven structure appears in Open Self Service, which supports multiple headless CMS options behind a consistent integration layer.</p><p>This change did not just replace one CMS with another. It moved content closer to the core of the digital platform. With Strapi controlling both content and parts of the frontend configuration, it became much easier to:</p><ul><li>expose relevant knowledge exactly where customers make decisions,</li><li>keep layouts and navigation consistent across applications,</li><li>evolve the structure of the portal without changing backend code,</li><li>serve the same content to multiple channels through APIs, without duplicating editorial work.</li></ul><h4>Reliability, deployments and composable benefits</h4><p>Composable architecture also changes how deployments and maintenance are handled. With Osadkowski’s platform, individual services and applications can be updated independently, using patterns such as rolling updates where appropriate. This makes it possible to evolve parts of the system without freezing all customer-facing functionality.</p><p>In practice, this means that selected areas of the portal can remain available even when specific components are being updated. For example, content sections and account views can stay accessible while deeper transactional capabilities are temporarily limited during planned maintenance. Having clear integration boundaries between frontend, BFF, OroCommerce and other backend systems makes these kinds of controlled changes easier to plan, communicate and execute.</p><p>The same mindset informs how Open Self Service is designed: integrations are explicit, failure modes are considered from the start, and frontends are built to degrade gracefully instead of failing completely when one dependency is being updated.</p><h4>Hybrid mobile app: extending one frontend to multiple channels</h4><p>While the web portal currently serves as the primary entry point, Osadkowski is considering the introduction of a hybrid mobile application. Instead of developing a separate native frontend, the team is evaluating the option of wrapping the existing React.js application in a WebView-based shell connected to the BFF. This approach reuses the same UI components, routing and domain models across browser, PWA and native mobile touchpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LNWjsymMeyMna1au.png" /></figure><p>From a user’s perspective, this means consistent journeys across devices: the same account, the same self-service and commerce flows, adapted to mobile form factors.</p><p>From a delivery perspective, the hybrid model is cost-efficient. Most changes are implemented once in the web frontend and automatically propagate to mobile, while the native shell focuses on platform-specific concerns such as app store distribution, navigation behaviour, update prompts or other native capabilities.</p><p>Under the hood, the application detects when it is running in the native shell (for example, through a tailored user-agent), adapts navigation to platform conventions and ensures that session handling behaves correctly inside WebViews. These are relatively small, isolated changes compared to building and maintaining a fully separate native codebase, and they align well with the composable principle of reusing stable contracts and components across channels.</p><p>While this mobile app is still upcoming, similar hybrid patterns have already been validated in other Hycom accelerators and projects. That experience reinforces one of the assumptions behind Open Self Service: a single composable frontend should be able to power multiple channels — browser, PWA and mobile — without duplicating business logic or integration work.</p><h3>What this project contributed to Open Self Service</h3><p>The Osadkowski project started before the Orange Energia client portal, but both initiatives share a similar DNA: a composable frontend sitting on top of multiple backend systems, with a CMS coordinating both content and parts of the frontend configuration.</p><p>From a product and architecture perspective, Osadkowski influenced several ideas that later became more formalized in Open Self Service:</p><ul><li>the distinction between BFFs that only aggregate data and BFFs that also normalize it into reusable domain models,</li><li>the importance of treating the CMS as a central tool for managing not just content, but also page structure and rendered blocks,</li><li>patterns for integrating complex B2B commerce engines like OroCommerce into a frontend that must remain backend-agnostic over time.</li></ul><p>Open Self Service packages these lessons into a reusable, open-source framework for building customer and partner portals, self-service applications and B2B e-commerce frontends.</p><p>The composable patterns validated in the project help teams start with a sustainable architecture from day one, instead of recreating the same foundation from scratch on every project. They also reinforce several concrete design choices in O2S:</p><ul><li>domain-focused BFFs,</li><li>a pragmatic monorepo approach to shared components,</li><li>CMS-driven configuration of frontend structure,</li><li>and an architecture that naturally extends to additional channels such as hybrid mobile apps.</li></ul><p>If you want to see how these patterns look in an open-source implementation, you can explore Open Self Service — its features, architecture and code — starting from the <a href="https://www.openselfservice.com/features"><strong>website</strong></a>, <a href="https://www.openselfservice.com/docs"><strong>docs</strong></a> and <a href="https://github.com/o2sdev/openselfservice"><strong>GitHub repo</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134c5338eea9" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/composable-b2b-portal-self-service-commerce-and-lessons-learned-134c5338eea9">Composable B2B portal: self-service, commerce and lessons learned</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Contentful with Live Preview into composable Next.js apps]]></title>
            <link>https://javascript.plainenglish.io/integrating-contentful-with-live-preview-into-composable-next-js-apps-b95925189817?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95925189817</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[contentful]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 07:50:12 GMT</pubDate>
            <atom:updated>2025-12-03T18:58:38.460Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of modern web development, composable architectures are becoming increasingly popular. These architectures allow developers to build applications by combining independent services rather than relying on monolithic solutions. One key component in many composable architectures is a headless CMS, which provides content management capabilities without dictating how that content is presented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQ8nmYImb6g99SWjXvadmA.png" /></figure><p>At <a href="https://www.openselfservice.com/"><strong>Open Self Service</strong></a>, we’ve integrated Contentful as our next headless CMS, following our successful <a href="https://medium.com/@marcin_krasowski/building-composable-frontends-with-strapi-and-next-js-3cd3baca11f7"><strong>implementation with Strap</strong></a><strong>i</strong>. This transition highlights key strength of composable architecture, and the data normalization approach that Open Self Service is built on. Replacing API services (which a headless CMS essentially is) becomes a relatively straightforward process that requires no changes to the frontend application, though it requires some upfront work in terms of creating a module that integrates that new service. This decoupling between the frontend and backend services is a fundamental principle of our architecture.</p><p>We’ll explore here how we implemented the Contentful integration, with a particular focus on the Live Preview feature, which allows content editors to see their changes in real-time.</p><h3>GraphQL Implementation</h3><p>When integrating with Contentful, we chose to use their GraphQL API rather than the REST API. GraphQL offers several advantages for our use case:</p><ol><li>We can request exactly the data we need, reducing over-fetching and improving performance.</li><li>The GraphQL schema provides clear documentation of available data and helps catch errors at build time with TypeScript data models.</li><li>We can fetch complex, nested data structures in a single request.</li></ol><p>We use GraphQL code generation (via <a href="https://the-guild.dev/graphql/codegen">graphql-codegen</a>) to create type-safe queries and a strongly typed SDK. This approach ensures that our queries are valid and that we get proper TypeScript types for the responses:</p><pre>import { CodegenConfig } from &#39;@graphql-codegen/cli&#39;;<br><br>const config: CodegenConfig = {<br>    schema: `https://graphql.contentful.com/content/v1/spaces/${process.env.CF_SPACE_ID}/environments/${process.env.CF_ENV}?access_token=${process.env.CF_TOKEN}`,<br>    documents: &#39;./src/**/*.graphql&#39;,<br>    generates: {<br>        &#39;generated/contentful.ts&#39;: {<br>            plugins: [&#39;typescript&#39;, &#39;typescript-resolvers&#39;, &#39;typescript-operations&#39;, &#39;typescript-graphql-request&#39;],<br>        },<br>        &#39;./graphql.schema.json&#39;: {<br>            plugins: [&#39;introspection&#39;],<br>        },<br>    },<br>};<br>export default config;</pre><p>This configuration:</p><ol><li>Fetches the schema directly from Contentful’s GraphQL API and saves it locally for IDE/tooling support.</li><li>Looks for GraphQL documents (queries, mutations, fragments) in all .graphql files.</li><li>Generates TypeScript data model and an SDK in generated/contentful.ts.</li></ol><p>The generated code includes types for all Contentful content models, as well as SDK methods for executing GraphQL operations:</p><pre>// Example of a GraphQL query defined in a .graphql file<br>query getPage($slug: String!, $locale: String!, $preview: Boolean) {<br>    pageCollection(locale: $locale, where: { slug: $slug }, limit: 1, preview: $preview) {<br>        items {<br>            ...Page<br>        }<br>    }<br>}<br><br>// This query is transformed by graphql-codegen into TypeScript code:<br>export const GetPageDocument = gql`<br>    query GetPage($slug: String!, $locale: String!, $preview: Boolean) {<br>        pageCollection(<br>            where: { slug: $slug }<br>            locale: $locale<br>            preview: $preview<br>            limit: 1<br>        ) {<br>            items {<br>                ...Page<br>            }<br>        }<br>    }<br>    ${PageFragmentDoc}<br>`;<br><br>// Along with strongly typed variables and return types:<br>export type GetPageQueryVariables = Exact&lt;{<br>  slug: Scalars[&#39;String&#39;][&#39;input&#39;];<br>  locale: Scalars[&#39;String&#39;][&#39;input&#39;];<br>  preview?: InputMaybe&lt;Scalars[&#39;Boolean&#39;][&#39;input&#39;]&gt;;<br>}&gt;;<br>export type GetPageQuery = {<br>  pageCollection?: {<br>    items: Array&lt;{<br>      slug?: string | null;<br>      // ... other page fields<br>    } | null&gt; | null<br>  } | null<br>};</pre><p>The SDK uses these code fragments to provide strongly typed functions for executing the queries, while using <a href="https://www.npmjs.com/package/graphql-request">graphql-request library</a> to create GraphQL client.</p><pre>export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {<br>    return {<br>        getPage(variables: GetPageQueryVariables, requestHeaders?: RequestInit[&#39;headers&#39;]): Promise&lt;GetPageQuery&gt; {<br>            return withWrapper((wrappedRequestHeaders) =&gt;<br>                client.request&lt;GetPageQuery&gt;(GetPageDocument, variables, {<br>                    ...wrappedRequestHeaders,<br>                    ...requestHeaders,<br>                }),<br>            );<br>        },<br>        // ... other SDK methods<br>    };<br>}</pre><p>In our application, we use this generated SDK to create a <a href="https://nestjs.com/">NestJS</a> service that uses both the Contentful Delivery API (for published content) and Preview API (for draft content).:</p><pre>@Injectable()<br>export class GraphqlService {<br>    private readonly deliveryClient: GraphQLClient;<br>    private readonly previewClient: GraphQLClient;<br>    private readonly deliverySdk: Sdk;<br>    private readonly previewSdk: Sdk;<br><br>    constructor(private readonly config: ConfigService) {<br>        // Initialize clients for both delivery (published) and preview (draft) content<br>        this.deliveryClient = new GraphQLClient(baseUrl, {<br>            headers: { Authorization: `Bearer ${process.env.CF_TOKEN}` },<br>        });<br>        this.previewClient = new GraphQLClient(baseUrl, {<br>            headers: { Authorization: `Bearer ${process.env.CF_PREVIEW_TOKEN}` },<br>        });<br>        // Create SDK instances for both clients<br>        this.deliverySdk = getSdk(this.deliveryClient);<br>        this.previewSdk = getSdk(this.previewClient);<br>    }<br><br>    // Helper method to get the appropriate SDK based on preview flag<br>    private getSdk(preview?: boolean | null): Sdk {<br>        return preview === true ? this.previewSdk : this.deliverySdk;<br>    }<br><br>    // Type-safe methods for fetching content<br>    public getPage(params: GetPageQueryVariables) {<br>        return this.getSdk(params.preview).getPage(params);<br>    }<br>}</pre><p>By combining GraphQL with code generation, we’ve created a robust and developer-friendly data fetching system. The generated TypeScript data model ensures complete type safety throughout our application, eliminating runtime errors related to data structure mismatches.</p><p>This implementation also provides compile-time validation of our GraphQL operations, catching potential errors before they reach production, together with IDE code completion both when writing queries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEyEFBso2dkMbZpkBVwztw.png" /></figure><p>and also when using generated types directly in the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-WB5LWZ1cEpaUXdM0sLjw.png" /></figure><p>Perhaps most importantly for content editors, our implementation enables seamless switching between published and draft content, creating a smooth workflow between content creation and preview.</p><h3>Content Type Modeling</h3><p>Our approach to content type modeling in Contentful is centered around flexibility and reusability. We’ve designed our content types to be composable, allowing content editors to build pages by combining different components.</p><p>The core of our content model is the Page content type, which represents a single page in our application. Each page has a template, which defines the layout of the page, and slots, which contain the components that make up the page content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37g5XpbNb6M2dQzjiOWhKg.png" /></figure><p>Here’s how we map a Contentful page to our application’s data model:</p><pre>export function mapPage(entryPage: PageFragment): CMS.Model.Page.Page {<br>    if (!entryPage) {<br>        throw new NotFoundException();<br>    }<br><br>    return {<br>        id: entryPage.sys.id,<br>        slug: entryPage.slug,<br>        title: entryPage.title,<br>        description: entryPage.description,<br>        template: mapTemplate(entryPage.template),<br>        seo: mapSeo(entryPage.seo),<br>    };<br>}</pre><p>We have also prepared mappers for specific content blocks, such as FAQs, which transform Contentful data into our application’s data model. These mappers use the generated fragment types to ensure type safety:</p><pre>// First, we define the GraphQL fragment for the FAQ component<br>fragment FaqComponent on BlockFaq {<br>    __typename<br>    sys {<br>        ...Sys<br>    }<br>    title<br>    subtitle<br>    itemsCollection {<br>        items {<br>            sys {<br>                ...Sys<br>            }<br>            title<br>            content<br>        }<br>    }<br>}<br><br>// graphql-codegen generates a TypeScript type for this fragment:<br>export type FaqComponentFragment = {<br>    __typename: &#39;BlockFaq&#39;,<br>    sys: { id: string },<br>    title?: string | null,<br>    subtitle?: string | null,<br>    itemsCollection?: {<br>        items: Array&lt;{<br>            sys: { id: string },<br>            title?: string | null,<br>            content?: string | null<br>        } | null&gt; | null<br>    } | null,<br>};</pre><p>Then we use this generated type in our mapper:</p><pre>export const mapFaqBlock = ({<br>    isPreview,<br>    ...data<br>}: FaqComponentFragment &amp; { isPreview?: boolean }): CMS.Model.FaqBlock.FaqBlock =&gt; {<br>    switch (data.__typename) {<br>        case &#39;BlockFaq&#39;:<br>            return {<br>                id: data.sys.id,<br>                title: data.title,<br>                subtitle: data.subtitle,<br>                items: data.itemsCollection?.items.map(<br>                    (item): CMS.Model.FaqBlock.FaqItem =&gt; ({<br>                        title: item.title!,<br>                        content: item.content!,<br>                    }),<br>                ),<br>            };<br>    }<br><br>    throw new NotFoundException();<br>};</pre><p>This approach allows us to have a clean separation between our content model in Contentful and our application’s data model, making it easier to evolve each independently.</p><h3>Live Preview Integration</h3><p>One of the most powerful features of Contentful is Live Preview, which allows content editors to see their changes in real-time as they edit content. Implementing Live Preview in a composable architecture presents some unique challenges:</p><ol><li>Our architecture includes an API composition layer that aggregates and transforms data from various sources, including Contentful. This layer adds complexity to the Live Preview implementation because changes made in Contentful need to flow through this layer before they can be displayed in the preview.</li><li>We designed our architecture to be CMS-agnostic, allowing us to potentially switch to a different CMS in the future. However, Live Preview implementations are typically CMS-specific, making it challenging to create a generic solution.</li><li>Our mappers transform Contentful data into our application’s data model, which can make it difficult to map changes back to the original Contentful fields for Live Preview.</li></ol><p>To address these challenges, we’ve added metadata to our mapped data structures, including Contentful entry IDs and field names, to enable the Live Preview SDK to map changes back to the original Contentful fields. This metadata is only included in the response while the app is run in preview/draft mode so that there would be no unnecessary data for regular users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUlIiit5BL7mgYfa2WOnFQ.png" /></figure><p>We’ve also created a wrapper around the Contentful Live Preview SDK that abstracts away Contentful-specific details, making it easier to potentially support other CMSs in the future.</p><h4>Live Preview approaches across headless CMSes</h4><p>It’s important to note that live preview functionality varies significantly between different headless CMSes. This makes building a CMS-agnostic architecture a bit more challenging, as each system may require a different integration approach.</p><p>Some CMSes, like Contentful, use an approach with explicit connection between the app and the CMS editor. In this model, the CMS provides an SDK that adds special data attributes to DOM elements. These attributes create a connection between rendered content and the corresponding content in the CMS. When a content editor clicks on an element in the preview, the SDK uses these attributes to identify which field to edit in the CMS interface. Changes made in the CMS are pushed to the preview in real-time through WebSockets or similar technologies.</p><p>Other CMSes take a different approach using content <a href="https://www.sanity.io/docs/visual-editing/stega#fad3406bd530">source maps with steganography</a>. Content source maps are metadata that map rendered content back to its source in the CMS, similar to how source maps work in JavaScript. Stega (steganography) embeds invisible metadata within the content itself, often using techniques like invisible Unicode characters or subtle CSS variations.</p><p>Each approach has its trade-offs. Data attributes are more explicit but can add DOM clutter, while stega approaches are more elegant but potentially more fragile. Understanding these differences is crucial when designing a CMS-agnostic architecture that needs to support live preview across multiple systems.</p><p>While content source maps and stega approaches offer elegant solutions for direct integrations, they present significant challenges for architectures with API composition layers like ours. The transformation process in our composition layer can corrupt or disconnect the embedded metadata that stega relies on, as our normalization restructures content and breaks the carefully crafted patterns of invisible characters.</p><p>Our architecture requires mapping between our normalized data model and the CMS’s original structure, whereas content source maps typically assume a more direct relationship without an intermediate transformation layer. Additionally, our data aggregation and transformation process, which often combines multiple API calls, conflicts with stega’s assumption of a direct, synchronous relationship between CMS and rendered content.</p><p>This led us to favor Contentful’s explicit data attributes approach, which proved more resilient with our API composition layer and made it easier to maintain connections between transformed data and original Contentful entries.</p><h4>Metadata</h4><p>The metadata is a crucial part of our Live Preview implementation. It serves as a bridge between our application’s data model and Contentful’s content structure, enabling real-time editing and inspection of content directly from the frontend. It serves several important functions:</p><ol><li>It maps our internal property names back to the original Contentful field names, allowing the Live Preview SDK to know which fields to update when content is changed in the Contentful editor.</li><li>It includes Contentful entry IDs, which are necessary to identify specific content entries in the Contentful system.</li><li>For complex components with nested content (like FAQ items), the metadata maintains the hierarchical structure, ensuring that edits to nested content are properly tracked.</li></ol><p>The metadata is only included when the application is in preview mode, ensuring that regular users don’t receive unnecessary data.</p><p>Here’s how we add metadata to our mapped data structures:</p><pre>export const mapFaqBlock = ({<br>    isPreview,<br>    ...data<br>}: FaqComponentFragment &amp; { isPreview?: boolean }): CMS.Model.FaqBlock.FaqBlock =&gt; {<br>    switch (data.__typename) {<br>        case &#39;BlockFaq&#39;:<br>            return {<br>                // other field mapping as before<br>                id: data.sys.id,<br>                // mapping Contentful field names into our internal properties<br>                meta: isPreview<br>                    ? {<br>                          __id: data.sys.id,<br>                          title: &#39;title&#39;,<br>                          subtitle: &#39;subtitle&#39;,<br>                          items: data.itemsCollection?.items.map((item) =&gt; ({<br>                              __id: item.sys.id,<br>                              title: &#39;title&#39;,<br>                              content: &#39;content&#39;,<br>                          })),<br>                      }<br>                    : undefined,<br>            };<br>    }<br><br>    throw new NotFoundException();<br>};</pre><p>Here’s an example of what the metadata object looks like for a FAQ component at runtime:</p><pre>{<br>  // The Contentful entry ID for this FAQ block<br>  __id: &quot;6JhYyIcNVMrBnvQRpz9ItW&quot;,<br><br>  // Maps our &#39;title&#39; property to Contentful&#39;s &#39;heading&#39; field<br>  title: &quot;heading&quot;,<br><br>  // Maps our &#39;subtitle&#39; property to Contentful&#39;s &#39;subheading&#39; field<br>  subtitle: &quot;subheading&quot;,<br><br>  // Nested metadata for FAQ items<br>  items: [<br>    {<br>      // The Contentful entry ID for this FAQ item<br>      __id: &quot;1xF7kLmPqS3TvR8zWj2YuB&quot;,<br><br>      // Maps our &#39;title&#39; property to Contentful&#39;s &#39;heading&#39; field<br>      title: &quot;heading&quot;,<br><br>      // Maps our &#39;content&#39; property to Contentful&#39;s &#39;content&#39; field<br>      content: &quot;content&quot;<br>    },<br>    {<br>      __id: &quot;9cD4hGbN2pQ7vE5xZm1KuL&quot;,<br>      title: &quot;heading&quot;,<br>      content: &quot;content&quot;<br>    }<br>  ]<br>}</pre><h4>Client SDKs</h4><p>Our Live Preview implementation uses Contentful’s Live Preview SDK, which provides React components and hooks for enabling Live Preview in our application:</p><pre>import { ContentfulLivePreviewInitConfig } from &#39;@contentful/live-preview&#39;;<br>import { ContentfulLivePreviewProvider } from &#39;@contentful/live-preview/react&#39;;<br>import React, { ReactNode } from &#39;react&#39;;<br><br>interface LivePreviewProviderProps extends Omit&lt;ContentfulLivePreviewInitConfig, &#39;children&#39;&gt; {<br>    children: ReactNode;<br>}<br><br>export function LivePreviewProvider({ children, ...props }: LivePreviewProviderProps) {<br>    return &lt;ContentfulLivePreviewProvider {...props}&gt;{children}&lt;/ContentfulLivePreviewProvider&gt;<br>}</pre><p>We also created a custom hook to make it easier to use the Live Preview inspector mode in our components. It uses the metadata to create HTML attributes that the Contentful Live Preview SDK can use to highlight and edit the content. When a content editor clicks on the title in the preview, they’re taken directly to the corresponding field in the Contentful editor.</p><pre>import { useContentfulInspectorMode } from &#39;@contentful/live-preview/react&#39;;<br><br>export const useInspector = () =&gt; {<br>    const inspectorProps = useContentfulInspectorMode();<br><br>    return &lt;T&gt;(data: Props&lt;T&gt; | undefined, name: keyof Props&lt;T&gt;): DataAttribute =&gt; {<br>        if (!data) return {};<br><br>        const attributes = inspectorProps({<br>            entryId: data.__id,<br>            fieldId: data[name],<br>        });<br><br>        return attributes;<br>    };<br>}</pre><p>When a content editor uses Live Preview and clicks on a component in the preview, our useInspector hook uses this metadata to generate the necessary attributes for the Live Preview inspector:</p><pre>const FaqItem = ({ item, meta }) =&gt; {<br>    const inspector = useInspector();<br><br>    return (<br>        &lt;div className=&quot;faq-item&quot;&gt;<br>            &lt;h3 {...inspector(meta, &#39;title&#39;)}&gt;{item.title}&lt;/h3&gt;<br>            &lt;div {...inspector(meta, &#39;content&#39;)}&gt;{item.content}&lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><h3>Conclusion</h3><p>The most significant innovation in our implementation was the metadata pattern we developed to bridge our normalized data model with Contentful’s structure. This pattern was essential for Live Preview functionality to work with our composable architecture, maintaining context about the origin of data while enabling real-time content editing.</p><p>We faced a fundamental challenge: how to leverage Contentful’s powerful Live Preview capabilities while maintaining our CMS-agnostic architecture. Our thin abstraction layers combined with the metadata pattern showed us that pragmatic integration sometimes outweighs architectural purity.</p><p>Our API layer transforms Contentful’s raw data into a normalized format that our frontend components expect. For Live Preview to work, we needed to maintain bidirectional mapping between these transformed structures and their original Contentful counterparts, which required careful tracking of entry IDs and field names throughout the transformation process.</p><p>The composition layer processes data asynchronously, potentially combining multiple API calls. This created timing challenges for Live Preview, which expects near-instantaneous updates. We had to implement optimistic UI updates and sophisticated caching strategies to maintain a responsive editing experience.</p><p>For features providing significant value to content editors, like Live Preview, we found that direct integration with careful abstraction boundaries was the right approach. The key was making these decisions consciously rather than strictly adhering to architectural principles.</p><p>If you’re implementing Contentful or another headless CMS in a composable architecture, we hope these insights provide valuable guidance for your own integration journey.</p><p>Hit us on <a href="https://discord.gg/4R568nZgsT"><strong>Discord</strong></a> if you have any questions or would like to get some more details. If you’re interested in our project, visit <a href="https://www.openselfservice.com/"><strong>our website</strong></a> where you can find more info about Open Self Service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95925189817" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/integrating-contentful-with-live-preview-into-composable-next-js-apps-b95925189817">Integrating Contentful with Live Preview into composable Next.js apps</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What we learned building a Next.js, Contentful and Keycloak client portal and how it evolved]]></title>
            <link>https://javascript.plainenglish.io/what-we-learned-building-a-next-js-ef0f6713fc0b?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef0f6713fc0b</guid>
            <category><![CDATA[contentful]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 00:00:47 GMT</pubDate>
            <atom:updated>2025-11-28T07:51:49.478Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What we learned building a Next.js, Contentful and Keycloak client portal and how it evolved into a composable frontend framework</strong></h3><p>Digital self-service is no longer a “nice to have” in energy and utilities. Customers expect instant access to data, transparent communication, and the ability to take action without waiting for support. For providers, this means one thing: the traditional model of service delivery must evolve into a flexible, digital-first environment.</p><p>Orange Energia — one of the most innovative energy providers in Poland — took this challenge seriously. Their goal was clear: build a modern, unified client portal that would simplify customer communication, reduce operational load, and create a scalable foundation for future services. The portal was known as “Moja Orange Energia” and was delivered for Orange Energia — then a company within the Orange Group and now part of the Fortum Group.</p><p>The project became one of the first large-scale composable portal implementations in the Polish energy sector. On the technical side, the portal combined a React/Next.js-based frontend with a NestJS Backend for Frontend layer allowing OpenAPI-first integration approach. It integrated with Orange Energia’s billing engine, CRM systems, metering and usage data platforms, IAM service based on Keycloak, a headless CMS (Contentful), and search infrastructure powered by Elasticsearch.</p><p><strong>The system we delivered played a crucial role in shaping the components and architectural assumptions that evolved into </strong><a href="https://openselfservice.com/"><strong>Open Self Service</strong></a> — our ready-to-deploy, modular frontend for digital self-service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A-3j3jGaSMNtSPRe.jpg" /></figure><h3>Why Orange Energia needed a composable digital portal</h3><p>As a fast-growing energy provider supporting both consumers and businesses, Orange Energia faced challenges common in the sector. Growing customer expectations demanded full visibility into contracts, usage, invoices, and service requests. There was increasing pressure to reduce cost-to-serve through automation and self-service. Without an existing digital self-service portal, most interactions still flowed through call centers and manual back-office workflows, and the volume of requests and manual work performed by service teams continued to grow.</p><p>Orange Energia wanted a portal that would:</p><ul><li>give customers real-time access to their energy data and documents,</li><li>unify multiple service processes in one experience,</li><li>support future expansion without risky rebuilds,</li><li>and enable quick delivery cycles instead of long monolithic releases.</li></ul><h3>Why composable architecture made the difference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ralovwhv53XzkMddPD7Rag.png" /></figure><p>The strategic decision to build Orange Energia’s portal in a composable model brought benefits that go far beyond the initial MVP.</p><ol><li><strong>Faster time-to-market</strong>: Each capability — billing, consumption data, applications, notifications — was delivered as a separate, independent component. This enabled parallel workstreams, shorter release cycles, and faster value delivery to end users. Teams could work on different features simultaneously without blocking each other.</li><li><strong>Flexibility to replace or upgrade components</strong>: Orange Energia can modernize any part of the portal without rewriting the rest. This includes replacing the CMS, adding new payment methods, extending business workflows, or rolling out new analytics widgets. This flexibility is essential in the energy sector, where regulatory, technical, and customer requirements change rapidly.</li><li><strong>Smooth integration with existing systems</strong>: Composable architecture enabled seamless connection with billing and settlement engines, CRM systems, meter data management systems, identity and security services, and notification and workflow tools. Instead of building long, monolithic integrations, each module communicates through clear, API-based contracts.</li><li><strong>Ready for future scalability</strong>: With new processes emerging and having a future backlog planned — Orange Energia got a foundation that supports evolving business models, adding new customer journeys, and expanding the portal to new service lines.</li><li><strong>“Productization” path toward Open Self Service</strong>: The modular approach leveraged in this project became one of the key inputs for creating Open Self Service — a fully composable, industry-ready self-service platform based on the same principles.</li></ol><h3>How Orange Energia’s technical challenges shaped Open Self Service</h3><p>Building a composable portal for Orange Energia on top of Hycom’s accelerator required solving several technical challenges that directly influenced how we designed Open Self Service. From content modeling constraints to enterprise security requirements, each decision helped refine the platform-level patterns defined for this stack and confirmed which of them actually work in production.</p><h4>Content modeling and CMS flexibility<a href="https://www.openselfservice.com/blog/how-composable-client-portal-for-orange-energia-became-foundation-for-open-self-service#content-modeling-and-cms-flexibility">​</a></h4><p>Orange Energia used Contentful as their headless CMS, and we quickly appreciated its developer experience. Content editors found the interface intuitive, live preview worked smoothly, and data migration between spaces was straightforward.</p><p>However, we hit a practical constraint: the basic plan limited content types to 50, and we exceeded that limit during development. In hindsight, this was largely a consequence of our initial content modeling strategy — each page type received its own content type, plus supporting types for components, and some of these types grew quite large. We also discovered limits on the number of fields within a single content type, which prevented us from simply consolidating types. Because the project could not move to a higher subscription tier at that stage, we had to rethink how we structured content within the existing limits.</p><p>To reduce the pressure on content type limits for simple label content, we introduced a pattern based on storing multiple key-value pairs in a single JSON field, then building a custom Contentful app that rendered a simple form for editing these labels. This reduced content type usage for UI labels, button text, and form field labels.</p><p>The real lesson was about flexibility in content modeling. Not every organization can justify upgrading to higher-tier SaaS plans, and some prefer open-source alternatives. In O2S, we designed the CMS integration layer to be swappable — you can use Strapi, Contentful, or any other headless CMS that exposes a GraphQL or REST API.</p><p>More importantly, we changed our content modeling approach in later projects. Instead of creating a separate content type for each page type, O2S uses a single <a href="https://www.openselfservice.com/docs/integrations/cms/strapi/content-model#pages">Page content type</a> that can compose any number of reusable blocks. New pages don&#39;t require new content types. Blocks aren&#39;t tied to specific pages - they can be reused across the application. This makes content management more flexible and reduces the complexity of the content model.</p><h4>Security and API contracts</h4><p>Orange Energia’s security team had strict requirements across multiple areas of the platform, and aligning on them was a significant part of the collaboration.</p><p>One of these areas was the firewall support: it needed exact API specifications to allow known traffic patterns while blocking anything that didn’t match documented schemas. This meant we needed complete OpenAPI definitions for our Backend for Frontend (BFF) layer, including precise field formats, data types, and validation rules. Working through these constraints together gave us a much clearer view of how security requirements shape architecture and delivery processes.</p><p>Initially, our BFF implementation used TypeScript interfaces. However, NestJS decorators for generating OpenAPI schemas only work with classes, not interfaces. We refactored the codebase to use classes instead, enabling automatic OpenAPI schema generation from our NestJS controllers and DTOs.</p><p>To make this approach practical at scale, we defined DTO classes using @ApiProperty decorators and backed them with a shared set of reusable patterns. This avoided copying the same regular expressions and constraints across dozens of classes:</p><pre>export class User {<br>  @ApiProperty({ ...PATTERNS.USER_ID })<br>  id?: string;<br><br>  @ApiProperty({ ...PATTERNS.EMAIL })<br>  username?: string;<br><br>  @ApiProperty({ ...PATTERNS.NAME })<br>  firstName!: string;<br><br>  @ApiProperty({ ...PATTERNS.NAME })<br>  lastName!: string;<br><br>  @ApiProperty({ ...PATTERNS.EMAIL })<br>  email!: string;<br><br>  @ApiProperty({ ...PATTERNS.PHONE })<br>  phoneNumber?: string;<br><br>  @ApiProperty({ ...PATTERNS.LANG_CODE })<br>  lang!: string;<br><br>  @ApiProperty({ isArray: true, maxItems: 50, ...PATTERNS.CUSTOMER })<br>  customers?: Array&lt;string&gt;;<br>}</pre><p>The PATTERNS namespace centralized all OpenAPI and validation metadata - including regexes, lengths, descriptions, and examples:</p><pre>export namespace PATTERNS {<br>  export const EMAIL = {<br>    pattern:<br>      &quot;^[a-zA-Z0-9!#$%&amp;&#39;*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&amp;&#39;*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$&quot;,<br>    minLength: 5,<br>    maxLength: 320,<br>    description: &#39;Email&#39;,<br>    example: &#39;john.smith@mail.com&#39;,<br>  };<br><br>  export const PHONE = {<br>    pattern: &#39;^\\+?\\d{1,4}?[-.\\s]?\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$&#39;,<br>    minLength: 1,<br>    maxLength: 50,<br>    description: &#39;Phone number&#39;,<br>    example: &#39;+48 500 500 500&#39;,<br>  };<br><br>  export const NAME = {<br>    pattern: &#39;^([a-zA-Z0-9À-ÖØ-öø-ǿ \\xA0\\.\\,\\-\\/\\{\\}\\_\\:])*$&#39;,<br>    minLength: 1,<br>    maxLength: 256,<br>  };<br><br>  export const LANG_CODE = {<br>    pattern: &#39;^[a-zA-Z]{2}$&#39;,<br>    minLength: 2,<br>    maxLength: 2,<br>    description: &#39;Language code&#39;,<br>    example: &#39;EN&#39;,<br>  };<br><br>  export const CUSTOMER = {<br>    type: &#39;string&#39;,<br>    pattern: &#39;^\\d+$&#39;,<br>    minLength: 1,<br>    maxLength: 10,<br>    description: &#39;Customer ID&#39;,<br>    example: &#39;2000015&#39;,<br>  };<br><br>  // ... more reusable patterns<br>}</pre><p>To catch security compliance issues earlier, we built a custom validator that tested BFF responses against the OpenAPI schema during local development. This helped us identify mismatches before deploying to client environments, reducing back-and-forth with security teams. For example, when a string was returned instead of an integer in the id field, the validator responded with a structured error payload:</p><pre>{<br>  &quot;type&quot;: &quot;INVALID_REQUEST&quot;,<br>  &quot;data&quot;: [<br>    {<br>      &quot;name&quot;: &quot;id&quot;,<br>      &quot;value&quot;: [<br>        &quot;12345&quot;<br>      ],<br>      &quot;errors&quot;: [<br>        {<br>          &quot;instancePath&quot;: &quot;/0&quot;,<br>          &quot;schemaPath&quot;: &quot;#/items/type&quot;,<br>          &quot;keyword&quot;: &quot;type&quot;,<br>          &quot;params&quot;: {<br>            &quot;type&quot;: &quot;integer&quot;<br>          },<br>          &quot;message&quot;: &quot;must be integer&quot;<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><p>These experiences led to standardizing security practices in O2S. We configure required security headers using Helmet in the API harmonization layer, ensuring consistent security settings across deployments. The OpenAPI-first approach also became standard — when integrating with backends that don’t provide SDKs, we generate client code from OpenAPI specifications using tools like <a href="https://heyapi.dev/">heyapi.dev</a>, ensuring type safety and contract compliance from the start. The generation step itself is straightforward — for example, creating an Axios-based client from an oas.yaml file looks like this:</p><pre>import { createClient } from &#39;@hey-api/openapi-ts&#39;;<br><br>const generate = async () =&gt; {<br>  await createClient({<br>    input: &#39;./oas.yaml&#39;,<br>    output: &#39;./generated/zendesk&#39;,<br>    plugins: [<br>      {<br>        name: &#39;@hey-api/client-axios&#39;,<br>      },<br>    ],<br>  });<br>};<br><br>generate();</pre><h4>Frontend architecture and state management</h4><p>In Orange Energia, we maintained a shared UI library as a single package. This simplified initial implementation but reduced flexibility. Any change to a component required publishing the entire library, even for small updates.</p><p>O2S takes a more pragmatic approach. We don’t split components into separate packages upfront, but we’re ready to do so when reuse across multiple applications becomes necessary. This keeps the initial setup simple while maintaining the option for granular component distribution later.</p><p>For state management, Orange Energia used XState extensively — perhaps too extensively. We stored the entire application state in XState machines, which significantly increased complexity and the learning curve for new developers. XState is powerful for complex state machines, but it’s overkill for simple state management.</p><p>In O2S, we use React’s native state management. Global state lives in React Context providers, keeping the codebase approachable. We don’t rule out XState, but we’d only use it where a state machine provides clear value — in complex workflows or multi-step processes where state transitions need explicit modeling.</p><h4>UI theming and customization</h4><p>Orange Energia had full control over their UI because we built a custom Sass framework for component styling. Rebranding was straightforward — most changes could be done through variables, and component-specific adjustments were easy since we owned the component code.</p><p>O2S uses a different but equally flexible approach. We build components with <a href="https://ui.shadcn.com/">shadcn-ui</a> and Tailwind CSS. shadcn-ui provides copy-paste components that you own and can modify, while Tailwind’s utility classes make it easy to adapt components to different design guidelines. This combination gives teams the flexibility to customize the UI without fighting against a third-party library’s constraints.</p><h4>Authentication and identity management</h4><p>In Orange Energia we used Keycloak for authentication. To maintain visual consistency, we needed to style Keycloak’s login and registration flows to match the React application. Keycloak’s default UI uses Freemarker templates, which makes React integration challenging.</p><p>We used <a href="https://www.keycloakify.dev/">Keycloakify</a> — a library that provides React components for Keycloak integration. It allows embedding a React application that communicates with Keycloak and renders forms using existing UI components and styles. This approach is still used in O2S for Keycloak integrations.</p><p>The project also implemented user impersonation that can be triggered from a Backoffice application. Administrators can sign in as another user and perform actions in their name to troubleshoot issues or test user experiences. This required careful token management — generating impersonated tokens in the admin panel, storing them in cookies accessible on the main domain, and handling token substitution in next-auth. All impersonation actions were logged for audit purposes. While this specific implementation may not be needed in every deployment, the experience informed how we think about flexible authentication patterns in O2S.</p><h4>Key learnings for Open Self Service</h4><p>The Orange Energia project taught us that composable architecture isn’t just about technical flexibility — it’s about making pragmatic choices that balance immediate needs with long-term maintainability. We validated and refined many of the assumptions we had built into our accelerator: where composable modules make sense, how much reuse is realistic, and how strict API contracts need to be in real enterprise environments. We also learned to avoid over-engineering (like using XState everywhere), to design for replaceability (CMS integrations, UI libraries), and to build security and API contracts into the development workflow from the start.</p><p>These lessons directly shaped Open Self Service.</p><p>The platform is designed to be backend-agnostic, with swappable integrations. The content model is flexible enough to avoid vendor lock-in. Security practices are built in, not bolted on. And the architecture stays pragmatic — we use powerful tools where they add value, and simpler solutions where they’re sufficient.</p><p>The result is a framework that inherits the battle-tested patterns from Orange Energia (and other MACH-based projects we deilvered at Hycom) while remaining flexible enough for organizations with different constraints, budgets, and technical preferences.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iQCl-A4chpx5nev_.jpg" /></figure><p>The Orange Energia portal project shows how a well-executed composable approach can transform digital self-service in energy and utilities. Customers gained transparency, access, and control over their energy services. The organization reduced operational effort and manual workload, freeing service teams to focus on higher-value interactions. Technology teams gained a flexible, scalable foundation for next-generation digital services. The outcomes influenced the evolution of <strong>Open Self Service</strong> — built on real experience and proven components.</p><p>For energy providers navigating the pressure of rising expectations, new regulations, and growing complexity, composable client portals are no longer an experiment. They’re becoming the new digital standard.</p><p>Want to learn more about composable architecture for customer portals?</p><ul><li><a href="https://www.openselfservice.com/">Open Self Service website</a></li><li><a href="https://www.openselfservice.com/docs">Documentation</a></li><li><a href="https://github.com/o2sdev/openselfservice">GitHub repo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef0f6713fc0b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-we-learned-building-a-next-js-ef0f6713fc0b">What we learned building a Next.js, Contentful and Keycloak client portal and how it evolved</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging AI to speed up UI documentation in Storybook]]></title>
            <link>https://javascript.plainenglish.io/leveraging-ai-to-speed-up-ui-documentation-in-storybook-986d82be3ac2?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/986d82be3ac2</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 06:19:17 GMT</pubDate>
            <atom:updated>2025-10-17T00:57:46.764Z</atom:updated>
            <content:encoded><![CDATA[<p>The silent debt of undocumented components sooner or later occurs in many development projects. What begins as a few simple UI elements inevitably grows into a complex ecosystem of specialized components, each with their own variants, states, and quirks. Without proper documentation, even the most elegant component library becomes a labyrinth that team members must navigate through tribal knowledge, scattered comments, and outdated design files.</p><p>However, the tedious work of documenting dozens of components — a task that would typically consume days or weeks of developer time — can be transformed into an efficient, semi-automated process using AI-assisted tooling. This is the story of how we at <a href="https://www.openselfservice.com/"><strong>Open Self Service</strong></a> turned our documentation debt into a <a href="https://storybook-o2s.openselfservice.com/">comprehensive component library</a> in a fraction of the expected time, and we hope that it can help you as well in your own projects.</p><h3>Documentation debt</h3><p>As our project grew, our component library evolved from a handful of simple elements into a larger ecosystem. We started with using just base elements like buttons and inputs, but eventually ended up with a set of larger and more specialized components, each with their own variants, states, and quirks. Our development workflow began to show serious cracks:</p><ul><li>there was no easy way of decoupling component creation from other dev work — every time a new component was needed, we were also forced to prepare a (mocked) CMS response that included such a component just so that we had a playground where we could work</li><li>while the project is still very far from being too extensive to understand by one person, new team members had to spend too much time manually discovering the codebase to find out if something similar to what they needed has already been developed</li><li>but mainly, the documentation existed as a patchwork of comments, Figma designs, and “tribal knowledge” and never fully consolidated</li></ul><p>We had built a powerful system where some React components are mapped 1:1 with CMS blocks, allowing content editors to freely compose pages — but nobody had a complete picture of what was available or how it can be configured. Having an easy way to quickly preview available components — not only as a boring list in the CMS but also in a form of live demo — was slowly becoming a priority, and it was finally time to stop procrastinating on proper component documentation.</p><p>The mapping between our React components and CMS blocks wasn’t just a technical implementation detail — it was the foundation of our entire content strategy. Without proper documentation, we were building a powerful tool that nobody fully understood how to use.</p><p>So, how did we go from documentation debt to a comprehensive component library? Let’s dive into our journey of implementing Storybook and then supercharging the process with AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iwoLka3id_IQLrNGf4F5g.png" /></figure><h3>Getting started with Storybook</h3><p>Storybook isn’t just a documentation tool — it’s a development environment, a testing playground, and a communication bridge all rolled into one. Setting it up in a complex monorepo with Next.js is not always as straightforward as it’s <a href="https://storybook.js.org/docs/get-started/frameworks/nextjs">explained in official docs</a> and might need some further config and adjustments.</p><p>Let’s then start with a walk through our process of integrating Storybook into the Open Self Service project, a monorepo containing a Next.js app, a Nest.js-based API Composition layer, and other shared packages.</p><h4>Initial setup and file structure</h4><p>Naturally, we started with manually initializing the Storybook in our project:</p><pre>npx storybook@latest init</pre><h4>Provider setup and mocked data</h4><p>One of the first challenges we faced was setting up the necessary providers for our components. The types of components that we wanted to have documented included not only buttons and dropdowns, but also more complex blocks that are retrieving data from global contexts, like current locale or theme. They can also rely on some globally configured mechanisms like <a href="https://ui.shadcn.com/docs/components/tooltip">tooltips</a> that can define their own providers as well.</p><p>In a Next.js application, these providers would typically by placed somewhere high-level (like a layout or a page), but for Storybook, we needed to mock them manually, which thankfully can be easily done via the <a href="https://storybook.js.org/docs/configure#configure-story-rendering">preview file</a>:</p><pre>const preview: Preview = {<br>  decorators: [<br>      (Story) =&gt; (<br>          // while `messages` and `globalConfig` are normally fetched from an API,<br>          // here they are just local mocks<br>          &lt;NextIntlClientProvider locale=&quot;en&quot; messages={messages}&gt;<br>              &lt;GlobalProvider config={globalConfig}&gt;<br>                  &lt;TooltipProvider&gt;<br>                      &lt;Story /&gt;<br>                      &lt;Toaster /&gt;<br>                  &lt;/TooltipProvider&gt;<br>              &lt;/GlobalProvider&gt;<br>          &lt;/NextIntlClientProvider&gt;<br>      )<br>  ]<br>};</pre><p>The mock data was structured to mimic what would normally come from our API:</p><pre>// .storybook/data.ts (simplified)<br>export const globalConfig = {<br>    locales: [<br>        { value: &#39;en&#39;, label: &#39;EN&#39; },<br>        { value: &#39;de&#39;, label: &#39;DE&#39; },<br>        // other locales<br>    ],<br>    common: {<br>        header: {<br>            title: &#39;MOCK_HEADER_LOGON_EN&#39;,<br>            logo: {<br>                url: &#39;...&#39;,<br>                alt: &#39;Logo&#39;,<br>            },<br>            // navigation items, etc.<br>        },<br>        footer: {<br>            // footer configuration<br>        },<br>    },<br>};</pre><p>This approach allowed us to test components that depend on these providers without having to set up a full connection to the backend environment.</p><h4>Router mocking</h4><p>Since some of our components also use Next.js routing (e.g. to render links), we needed to mock the router as well. Once again, Storybook for Next.js provides utilities for this that can be used in the preview file:</p><pre>import { createNavigation } from &#39;@storybook/nextjs/navigation.mock&#39;;<br>import { createRouter } from &#39;@storybook/nextjs/router.mock&#39;;<br><br>createRouter({});<br>createNavigation({});</pre><p>which is enough to not immediately crash components that rely on the router. The routing itself will still not work (e.g. clicking links will not do anything), but that’s perfectly fine as we only need to document components in isolation from the main Next.js app.</p><h4>Environment variables</h4><p>We also needed to configure some environment variables for our local development environment. We did this in the ./storybook/main.ts file, where we use <a href="https://www.npmjs.com/package/dotenv">dotenv</a> to load the dedicated env file from the frontend app:</p><pre>import * as dotenv from &#39;dotenv&#39;;<br><br>dotenv.config({<br>    path: &#39;apps/frontend/.env.development&#39;,<br>    processEnv: env,<br>    quiet: true,<br>});<br>const config: StorybookConfig = {<br>    env: (config) =&gt; ({<br>        ...config,<br>        ...env,<br>    }),<br>    // other config<br>};</pre><h4>Our first manual story</h4><p>With the environment set up, we created our first story for the Button component:</p><pre>import type { Meta, StoryObj } from &#39;@storybook/nextjs&#39;;<br><br>import { Button } from &#39;./button&#39;;<br>const meta = {<br>    title: &#39;Elements/Button&#39;,<br>    component: Button,<br>    tags: [&#39;autodocs&#39;],<br>} satisfies Meta&lt;typeof Button&gt;;<br>export default meta;<br>type Story = StoryObj&lt;typeof meta&gt;;<br>export const Default: Story = {<br>    args: {<br>        children: &#39;Button&#39;,<br>        variant: &#39;primary&#39;,<br>        size: &#39;default&#39;,<br>    },<br>    render: ({ variant, size, children }) =&gt; (<br>        &lt;Button variant={variant} size={size}&gt;<br>            {children}<br>        &lt;/Button&gt;<br>    ),<br>}</pre><p>With this setup complete, we were ready to start creating stories for our components. However, with dozens of components to document, we needed a more efficient approach than manual creation.</p><h3>Leveraging AI for story creation</h3><p>Once we had our Storybook environment properly configured, we faced the daunting task of creating stories for dozens of components. Manual story creation would have been time-consuming and error-prone, so we turned to AI tools to accelerate the process.</p><p>We also wanted this task to be kind of an experiment to check how different AI tools handle such automation — without having to specify any additional configs or rules, and without more advanced task plannings. What we wanted was to test the simplest case — just give a few prompts to do a relatively simple task and get the result.</p><h4>Initial prompts</h4><p>The initial prompt itself was surprisingly simple, given that we already had one example of a story that we wanted. We started with the component at the top of the list, which happened to be <a href="https://storybook-o2s.openselfservice.com/?path=/docs/elements-accordion--docs">Accordion</a>:</p><pre>generate storybook stories for Accordion component in a similar way as it was done for Button</pre><p>As a long-time Webstorm user, I personally much prefer using that IDE in day-to-day work, which meant that we first tried it with <a href="https://www.jetbrains.com/junie/">Junie</a>. It’s a plugin that can be run directly from Webstorm, instead of switching to other tools or IDEs. Like Cursor, it also gives a step-by-step walkthrough of its process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Q6yFcUTW-BoPHBaTM1D_rg.png" /></figure><p>The output was predictably pretty ok, but could use some improvements:</p><pre>export const Default: Story = {<br>    args: {<br>        type: &#39;single&#39;,<br>    },<br>    render: ({ type }) =&gt; (<br>        &lt;Accordion type={type} className=&quot;w-full&quot;&gt;<br>            &lt;AccordionItem value=&quot;item-1&quot;&gt;<br>                &lt;AccordionTrigger&gt;Is it accessible?&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;Yes. It adheres to the WAI-ARIA design pattern.&lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>            &lt;AccordionItem value=&quot;item-2&quot;&gt;<br>                &lt;AccordionTrigger&gt;Is it styled?&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;<br>                    Yes. It comes with default styles that match the other components&amp;apos; aesthetic.<br>                &lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>            &lt;AccordionItem value=&quot;item-3&quot;&gt;<br>                &lt;AccordionTrigger&gt;Is it animated?&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;<br>                    Yes. It&amp;apos;s animated by default, but you can disable it if you prefer.<br>                &lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>        &lt;/Accordion&gt;<br>    ),<br>};<br><br>export const Multiple: Story = {<br>    args: {<br>        type: &#39;multiple&#39;,<br>    },<br>    render: ({ type }) =&gt; (<br>        &lt;Accordion type={type} className=&quot;w-full&quot;&gt;<br>            &lt;AccordionItem value=&quot;item-1&quot;&gt;<br>                &lt;AccordionTrigger&gt;First section&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;This is the first section content.&lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>            &lt;AccordionItem value=&quot;item-2&quot;&gt;<br>                &lt;AccordionTrigger&gt;Second section&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;This is the second section content.&lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>            &lt;AccordionItem value=&quot;item-3&quot;&gt;<br>                &lt;AccordionTrigger&gt;Third section&lt;/AccordionTrigger&gt;<br>                &lt;AccordionContent&gt;This is the third section content.&lt;/AccordionContent&gt;<br>            &lt;/AccordionItem&gt;<br>        &lt;/Accordion&gt;<br>    ),<br>};</pre><p>The first change that we did was to ask to create less separate stories if a single would suffice. We didn’t want to create a story for every single variant, type or size of a component — the ensuing combinations would quickly become overwhelming. So the next prompt was to:</p><pre>do not create a separate story for params like variant, size or type, and instead make them configurable through args</pre><p>which successfully reduced the number of generated stories to only one in this case.</p><p>Before we started generating stories by bulk, we’ve decided to give one more try for a bit more complex component. We picked <a href="https://storybook-o2s.openselfservice.com/?path=/story/elements-typography--default">Typography</a> for this, which we felt should show a few examples for headings, body text, or lists:</p><pre>generate storybook stories for Typography component in a similar way as it was done for Button and Accordion</pre><p>and it did exactly what I wanted and created a few examples that give a nice overview of the typography styles that are available in the app:</p><pre>export const Default: Story = {<br>    args: {<br>        children: &#39;Typography Example&#39;,<br>        variant: &#39;p&#39;,<br>    },<br>    render: ({ variant, children }) =&gt; &lt;Typography variant={variant}&gt;{children}&lt;/Typography&gt;,<br>};<br><br>export const Headings: Story = {<br>    render: () =&gt; (<br>        &lt;div className=&quot;space-y-4&quot;&gt;<br>            &lt;Typography variant=&quot;h1&quot;&gt;Heading 1&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;h2&quot;&gt;Heading 2&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;h3&quot;&gt;Heading 3&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;h4&quot;&gt;Heading 4&lt;/Typography&gt;<br>        &lt;/div&gt;<br>    ),<br>};<br>export const TextStyles: Story = {<br>    render: () =&gt; (<br>        &lt;div className=&quot;space-y-4&quot;&gt;<br>            &lt;Typography variant=&quot;subtitle&quot;&gt;Subtitle Text&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;small&quot;&gt;Small Text&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;body&quot;&gt;Body Text&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;large&quot;&gt;Large Text&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;p&quot;&gt;Paragraph Text&lt;/Typography&gt;<br>            &lt;Typography variant=&quot;lead&quot;&gt;Lead Text&lt;/Typography&gt;<br>        &lt;/div&gt;<br>    ),<br>};<br>// and a few more stories</pre><p>However, we’ve noticed one thing that occurred when Junie started working — since we did not actually provide any info where the Typography component was located, it had to find it on its own:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*yjH4EeJccsdaBzLpzja3_Q.png" /></figure><p>It managed perfectly fine, but we felt that helping out a bit could both speed up its job and save up on the number of tokens used, so we’ve tried <a href="https://storybook-dxp.openselfservice.com/?path=/story/elements-table--default">one more component</a>:</p><pre>generate storybook stories for `packages/ui/src/elements/table.tsx` component in a similar way as it was done for other components in that UI library</pre><p>which seemed to help, as it limited the number of steps needed and Junie knew exactly which component to analyze:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*ULDLgaNLk27KBMHN0s6PHw.png" /></figure><p>So far, the output was pretty much perfect, and it was time to try generating stories for all the remaining components with a single prompt — we did not want to manually generate each one, as the entire point of this task was to reduce the amount of manual work.</p><h4>Bulk story generation</h4><p>With a few examples of what the stories should look like, a more general prompt was needed, that pointed to the folder containing the components:</p><pre>generate storybook stories for components inside `packages/ui/src/elements` in a similar way as it was done for other components in that UI library; try to limit the number of separate stories if they can be handled by args for props like variant/size/type</pre><p>The first try with Junie was, however, less satisfactory. It somehow “forgot” about the rule to rely more on args, and instead once again tended to generate multiple stories where one or two would suffice, e.g. for the Checkbox component:</p><pre>export const Default: Story = {...};<br>export const Checked: Story = {...};<br>export const Disabled: Story = {...};<br>export const DisabledChecked: Story = {...};<br>export const WithLabel: Story = {...};<br>export const WithLabelChecked: Story = {...};<br>export const WithLabelDisabled: Story = {...};</pre><p>which, on the one hand, provided a more comprehensive instant overview of all possible states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*Ax1mfH3Y7yd1eMNS0NWUzQ.png" /></figure><p>But on the other hand, both increased the number of “pages” in Storybook and made it more cumbersome to maintain such a component. Documenting each new state or variant would make the stories too complex and might eventually become overwhelming.</p><p>All of these combinations could have been instead handled by only a single story with appropriate args, which makes it possible to simply configure them directly in Storybook:</p><pre>export const Default: Story = {<br>    args: {<br>        label: &#39;Accept terms and conditions&#39;,<br>        checked: false,<br>        disabled: false,<br>    },<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*TyQhAkw0asHENtgmByO5kw.png" /></figure><p>Such behavior occurred in more or less half of generated files, and it was easy to fix either manually (if most of what was needed was to remove unnecessary stories) or via another prompt.</p><p>So while generated stories were still mostly ok, only around a third of the components were analyzed, after which it simply stated the task as completed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*3h2JDyTMxqO6HjhRZH5Fog.png" /></figure><p>The worst part was that it reported that supposedly all components were handled, without any further prompts whether it should continue. Further prompts that asked to generate stories for the missing components gave similar results. Again, it was overeager in creating multiple stories for a single component, and each time only a part of the total components were being taken into account. All in all, we would have needed maybe up to 10 attempts to handle every single component in our project (as we had them split between three main categories/folders).</p><p>We decided to try exactly the same prompt in Cursor, and the outcome was a bit better, but still far from perfect, as it also generated only about a third of the necessary stories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*ivbEi69RD8abaN9IrLPaJA.png" /></figure><p>However, after another prompt to generate the rest, it successfully handled all the components in the folder, which meant that the overall number of prompts would be around half of what Junie needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Wgzt2UWFSap_y_XDAbiUDw.png" /></figure><p>As for the quality of the stories, it, like Junie, was a bit overzealous with creating multiple story variants where only one or two based on args would be enough. So we tried a few more prompts to narrow it down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*XIuMlHDJ-x-dbfsNgs3ssQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*aJvRtiL0aYPJvp2FOSnuZg.png" /></figure><p>The outcome still wasn’t perfect (there were still some stories that weren’t strictly necessary in our opinion), but it was good enough, and ready for the final, human verification process.</p><p>What was really nice was the form of the responses — unlike in Junie, Cursor gave very extensive summaries of what and how was modified, which was really helpful in estimating whether further prompts were still necessary. It proves that, as a more mature tool, Cursor still wins the AI battle in that regard.</p><h4>Manual review</h4><p>Once we’ve run through all the remaining components in our project — not only simple elements like buttons or inputs, but also more complex ones like cards or filters — it was time to do a final review of the results.</p><p>The manual review process was a critical step in ensuring the quality and accuracy of our AI-generated Storybook documentation. While AI tools significantly accelerated the initial creation, human oversight was still essential.</p><p>First, we needed to verify that each component’s stories accurately represented its functionality and available options. This involved checking that all important props were configurable through args and that the default values made sense in our application context.</p><p>What we discovered were several instances where there were incorrect props used. Some components had props that simply did not exist in the component — for example, for the Input component it tried to set label which couldn&#39;t event be provided; in some other cases, it misinterpreted the purpose of certain props. These issues were relatively easy to fix but would have caused confusion if left unaddressed.</p><p>As we’ve already seen, we also needed to manually adjust the number of stories for certain components. In some cases, the AI created too many separate stories where a single configurable one would be more maintainable. In other instances, particularly for complex components with distinct visual states, we actually needed to add more stories to properly showcase all the important variations — but these cases were thankfully very few.</p><blockquote>Actually, we found out that some generated stories reflected component states or variants that we ourselves would not think to document — which is another proof that such an approach not only speeds up development, but also helps in filling out blanks that would have been left by just human work.</blockquote><p>Overall, the manual review took less than half a day of focused work, which was a reasonable investment considering the time saved by using AI for the initial generation.</p><h3>Results and lessons learned</h3><p>Using AI for story creation provided significant benefits:</p><ol><li><strong>Reduced story creation time</strong> — we initially estimated that it would take a better part of a week to configure Storybook and then to write the stories for all components. While the initial configuration was still done manually, the bigger and definitely more monotonous work was largely done automatically. All in all, the entire process of creating documentation took less <strong>than 2 days</strong>, and much of it was done in the background. We’ve just submitted a prompt and let the AI do its own thing, only returning to it to check and occasionally fix the output, while focusing on some other more engaging tasks.</li><li>AI-generated stories also followed <strong>consistent patterns and naming conventions</strong>, which might be a minor gain but still reduced the risk of e.g. typos or other small mistakes if it was done manually.</li><li>We were positively surprised that the generated stories included some cases that we did not predict — like using banners or cards without a title (which was indeed optional, but was always provided in the rest of the app). This allowed us to make appropriate fixes and improvements in our components to properly handle some <strong>edge cases</strong> that have not been thought about earlier.</li></ol><p>The key was finding the right balance between AI automation and human oversight, ensuring that generated stories met our quality standards while maintaining the efficiency gains.</p><p>As for Junie vs Cursor, we felt that <strong>Cursor was overall better</strong> for this task, mostly because it handled bulk story creation better. Fewer prompts were necessary to both analyze all components, and also to apply further changes to generated stories.</p><p>The stories themselves were pretty much a <strong>similar quality in both cases</strong>, however. Both tools needed further prompts to accomodate the outcome to our needs, but neither was particularly better nor worse at it. The human verification and fixing was, of course, still very much required, of course, as it will be probably quite some time until the results are good enough that no supervision is a must.</p><p>It’s not the end of our plans to use the AI to reduce the time needed on such monotonous tasks. Similarly, we want to speed up the process of covering our project with unit tests, which, just like Storybook, were put off due to time constraints at the beginning of the project. Looking at the outcome of generating stories, we are quite certain that we can also achieve a high test coverage through a combination of automated AI testing and manual verification and adjustments.</p><p>Want to see how all of turned out? Check our project page and Storybook:</p><ul><li><a href="https://www.openselfservice.com/"><strong>Open Self Service website</strong></a></li><li><a href="https://storybook-o2s.openselfservice.com/"><strong>Storybook</strong></a></li></ul><p>We’d love your feedback — or even better, your contributions!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=986d82be3ac2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/leveraging-ai-to-speed-up-ui-documentation-in-storybook-986d82be3ac2">Leveraging AI to speed up UI documentation in Storybook</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring high frontend performance in composable Next.js apps]]></title>
            <link>https://javascript.plainenglish.io/ensuring-high-frontend-performance-in-composable-next-js-apps-5ec74b910665?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec74b910665</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 11:18:11 GMT</pubDate>
            <atom:updated>2025-10-14T10:35:48.553Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s web development landscape, composable architectures are gaining popularity for their flexibility and scalability. However, this approach introduces unique performance challenges. In this article, we will explore strategies and best practices for ensuring high frontend performance in composable applications, using <a href="https://www.openselfservice.com/"><strong>Open Self Service</strong></a> as a practical example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*FRNfmosDxXRyE9mZEuEOgA.png" /></figure><p>Open Self Service is a new framework for building enterprise-grade frontend solutions.</p><p>Our aim is to create an open-source set of tools that would allow building not only storefronts but different client-facing frontends, with the main focus on customer self-service apps. We want to be backend-agnostic and to some extent eliminate vendor lock-in, so that the frontends you build are safe from backend changes or upgrades. Composable architecture helps us to achieve all of this, so we need to introduce it before we show you how we deal with the performance challenges we faced.</p><h3>Understanding composable architecture</h3><h4>What is a composable architecture?</h4><p>In a nutshell, composable architecture is an approach to building applications by assembling modular, independent components that work together to create a complete solution — not only in the context of frontend, but across the whole system architecture, especially backend components. In the context of Open Self Service, we implemented this architecture in the form of a framework that enables the integration of multiple API-based services to provide a seamless user experience.</p><p>At its core, a few principles characterize composable architecture:</p><ul><li>applications are built from discrete, <strong>interchangeable components</strong> that can be developed, deployed, and scaled independently,</li><li>components communicate through <strong>well-defined APIs</strong> allowing for a wide flexibility in implementation details,</li><li><strong>decoupled systems</strong> (like frontend and backend components), which allows for each to evolve independently without affecting the other.</li></ul><p>Composable frontends provide significant advantages — you can be quite flexible in replacing backend components without disruption, are free from vendor lock-in through multi-backend integration, and are able to adapt to changing requirements with the ability to scale specific parts based on business demands.</p><h4>The separation of concerns</h4><p>In building Open Self Service, we chose to implement a clear separation of concerns between different layers of the application. While there are multiple ways to achieve composable architecture, our approach focuses on:</p><ul><li>complete <strong>separation of the presentation layer from the data and business logic layers</strong>, which allows each to evolve independently and enables the frontend to work seamlessly with multiple backend services</li><li>introduction of an intermediate <strong>API composition layer</strong> that acts as a bridge between the frontend and various backend APIs. This layer aggregates data from multiple sources and orchestrates data flows between systems. It efficiently combines static content with dynamic data while handling complex logic server-side, reducing browser processing overhead</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDFc-fMoqLx2AUMQIRHzVQ.png" /></figure><p>This kind of approach ensures backend service changes don’t require frontend code modifications (as long as that backend API is still backwards compatible), reducing maintenance overhead and increasing the overall flexibility.</p><h3>Performance strategies</h3><p>Now that we understand the architectural foundation, let’s explore the specific performance strategies that make composable applications fast and responsive. These techniques leverage the modular nature of our <a href="https://www.openselfservice.com/docs/main-components/blocks/">blocks system</a> to deliver optimal user experiences.</p><h4>Leveraging server components</h4><p>Probably one of the easiest “wins” is to take full advantage of <a href="https://nextjs.org/docs/app/getting-started/server-and-client-components">Next.js server components</a> to perform data fetching and initial rendering on the server. Each block in our system follows a clear separation between server and client components:</p><pre>export const OrderDetailsServer = async ({ id, orderId }) =&gt; {<br>    // Fetch block data from API composition layer<br>    const data = await sdk.blocks.getOrderDetails({ id: orderId });<br><br>    // Pass data to the client component<br>    return &lt;OrderDetailsClient id={id} {...data} /&gt;;<br>};</pre><pre>&#39;use client&#39;;<br><br>export const OrderDetailsClient = (props) =&gt; {<br>    // Render the actual component<br>    return (&lt;div&gt;...&lt;/div&gt;);<br>};</pre><p>This pattern ensures that data fetching occurs on the server, reducing client-side JavaScript bundle size and eliminating client-server waterfalls. The server component fetches the necessary data and passes it to a client component that handles interactivity.</p><h4>Streaming with Suspense</h4><p>By using server components, we can also easily implement component-level streaming using React’s Suspense, allowing parts of the page to load progressively rather than waiting for all data to be available. This approach ensures that slow-loading blocks (e.g. due to a slow or complex backend API calls) don’t block the rendering of faster ones, and users can start interacting with parts of the page while others are still loading.</p><p>Strategic placement of Suspense boundaries is crucial for optimal streaming performance. In our implementation, we place these boundaries at the block level rather than at the page level, allowing for more granular control over the loading experience:</p><ul><li>each block has its own Suspense boundary, allowing it to stream independently</li><li>more complex blocks can prepare the loading state to more or less represent how the component may actually look when it’s ready</li></ul><p>Let’s look at the OrderDetails block that is responsible for showing the users the details of one of their orders. It consists of a title, some tiles arranged in a grid, and a list of products that were purchased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVrdJC8yhGg8KOJhm4iRdw.png" /></figure><p>For optimal user experience — and to minimize layout shift that could occur during the page load — we prepare a similar layout in a “renderer” component that wraps the server component, using <a href="https://ui.shadcn.com/docs/components/skeleton">shadcn/ui’s Skeleton components</a>:</p><pre>export const OrderDetailsRenderer: React.FC&lt;OrderDetailsRendererProps&gt; = ({ id }) =&gt; {<br>  return (<br>    &lt;Suspense fallback={<br>      // skeleton grid that represents the layout of the component<br>      &lt;div className=&quot;w-full flex flex-col gap-6&quot;&gt;<br>        &lt;Loading bars={0} /&gt;<br>        &lt;div className=&quot;w-full flex flex-col md:flex-row gap-6&quot;&gt;<br>          &lt;div className=&quot;w-full flex flex-col gap-6&quot;&gt;<br>            &lt;div className=&quot;w-full flex flex-col md:flex-row gap-6&quot;&gt;<br>              &lt;Loading bars={2} /&gt;<br>              &lt;Loading bars={2} /&gt;<br>            &lt;/div&gt;<br>            &lt;Loading bars={2} /&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;w-full flex flex-col gap-6&quot;&gt;<br>            &lt;div className=&quot;w-full flex flex-col md:flex-row gap-6&quot;&gt;<br>              &lt;Loading bars={2} /&gt;<br>              &lt;Loading bars={2} /&gt;<br>            &lt;/div&gt;<br>            &lt;Loading bars={2} /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;Loading bars={8} /&gt;<br>      &lt;/div&gt;<br>    }&gt;<br>      // The component itself that is rendered when it&#39;s fully ready<br>      &lt;OrderDetailsServer id={id} /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>};</pre><p>When users enter this page, they will be able to:</p><ul><li>see meaningful loading states while data is being fetched</li><li>partly interact with the app (e.g. use the main navigation) even before the main content is fully ready</li></ul><p>And once the initial HTML is prepared server-side, it is immediately streamed to the browser, which can be seen on the following (artificially slowed-down so that loading states are actually visible) video showing a single block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*7AGKGCgiMfNeE5RQ2u93cQ.gif" /></figure><h4>Parallel data loading</h4><p>By using server components, we can enable parallel data loading, where multiple blocks on a page can fetch their data simultaneously rather than sequentially. Each block is responsible for its own data fetching, and the Suspense boundaries around each block allow them to load independently:</p><pre>export default function KnowledgeBasePage() {<br>    return (<br>        &lt;div&gt;<br>            &lt;SearchBlock /&gt;<br>            &lt;QuickLinksBlock /&gt;<br>            &lt;ArticleListBlock /&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>This effect is more interesting on pages that include more than one component, where each can take a different time to load (due to more complex backend logic, database access, network delays, or other causes).</p><p>Let’s take a look at <a href="https://demo-dxp.openselfservice.com/en/personal/help-and-support">another example</a>, this time a digital experience portal with a knowledge base area. Once more, each component is streamed to the browser as soon as it’s ready and is then available to interact with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*yOXEzBQjkZyHLuFHgLPuAw.gif" /></figure><p>While the fallback components are not sized to perfectly match their full counterparts, they don’t have to be. It’s enough for them to be “close enough”, just so that they can be visually similar to the final rendered components, especially considering that some content will be very dynamic when it e.g. depends on a CMS configuration.</p><p>As already mentioned, using Suspense has the additional benefit of reducing <a href="https://web.dev/articles/cls">Cumulative Layout Shift</a>. Let’s see what this process would look like if only one block did not provide any fallback states and notice how the article tiles “jump down” when the tiles above them appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*lnuRPAIYWzNnVWdzyw7N-w.gif" /></figure><p>While this is a mostly harmless example, just take a look at another, more dangerous example from <a href="https://web.dev/articles/cls">web.dev</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iVHCJ-URstRvnVtjkPOWmQ.gif" /></figure><p>It’s obvious that providing appropriate placeholders is critical not only to increase the overall performance (a high CLS will lower your Lighthouse score) but also to safeguard against potentially harmful actions.</p><p>So to sum up — this pattern eliminates the “waterfall” effect where one component must finish loading before the next one begins, significantly reducing the overall page load time. As a side effect, it can also provide a better user experience. Instead of using a single loader for the whole page or even delaying the page rendering until every single piece of data is fetched and ready for rendering, you can actually show the page loading progress.</p><h4>Component-level dynamic imports</h4><p>Beyond block-level code splitting, we use dynamic imports for heavy components within blocks. This is particularly beneficial, e.g., for data visualization components that rely on large third-party libraries:</p><pre>&#39;use client&#39;;<br><br>import dynamic from &#39;next/dynamic&#39;;<br><br>// Dynamically import the chart component to reduce initial bundle size<br>const StackedBarChart = dynamic(<br>    () =&gt; import(&#39;@o2s/ui/components/Chart/StackedBarChart&#39;)<br>      .then((module) =&gt; module.StackedBarChart),<br>);<br><br>export const PaymentsHistoryClient = ({ title, chartData }) =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;Typography&gt;{title}&lt;/Typography&gt;<br>            ...<br>            &lt;StackedBarChart chartData={chartData} /&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><p>In this example, the chart component (which depends on the <a href="https://recharts.org/">recharts library</a>) is dynamically imported only when needed (in other words, when that block is rendered on the frontend). Chart libraries are typically large and would significantly increase the initial bundle size, and typically not every page in the app will contain a chart component — so there’s no point in preloading a resource-heavy library before it’s actually necessary.</p><h4>API composition layer</h4><p>The API composition layer serves as a critical intermediary between frontend blocks and backend services. It can be implemented in a variety of different ways, but we chose to use <a href="https://nestjs.com/">Nest.js</a> as a framework which fits in nicely in the whole TypeScript-based tech stack.</p><p>As an example of what we can achieve using such architecture, let’s look at the service that is responsible for the endpoint for fetching data for the OrderDetails block:</p><pre>// Data aggregation from multiple sources<br>export class OrderDetailsService {<br>    constructor(<br>        // Service for fetching static content e.g. from some CMS<br>        private readonly cmsService: CMS.Service,<br>        // Service that returns dynamic data for the user from some backend API<br>        private readonly orderService: Orders.Service,<br>    ) {}<br><br>    getOrderDetailsBlock(params, query, headers) {<br>        const cms = this.cmsService.getOrderDetailsBlock({ <br>          ...query, <br>          locale: headers[&#39;x-locale&#39;] <br>        });<br>        const order = this.orderService.getOrder({ id: params.id });<br><br>        // Fetch data from both sources simultaneously<br>        return forkJoin([cms, order]).pipe(<br>            map((order) =&gt; {<br>                // Transform and combine data for the frontend app<br>                return mapOrderDetails(cms, order);<br>            }),<br>        );<br>    }<br>}</pre><p>This approach provides several benefits for the overall performance. Firstly, the composition layer combines data from multiple backend services into a single, optimized response that is specifically tailored for each block — returning only the information that block needs and nothing else, which eliminates overfetching.</p><p>Instead of making multiple API calls directly from the browser (e.g. for user actions like filtering or form submissions), the composition layer handles the communication with backend services, which reduces latency and bandwidth usage. The composition layer can fetch data from multiple sources in parallel using, for example, <a href="https://rxjs.dev/">RxJS observables</a>, optimizing the overall response time</p><p>Additionally, raw data from various backend services is transformed into a consistent format, which does not necessarily improve performance itself but allows the frontend to be implemented in an API-agnostic way.</p><h4>API-level caching</h4><p>However, in a composable architecture where each block independently fetches its own data, there’s a risk of redundant API calls to the same backend services. Therefore, it’s important to also provide a caching mechanism that can help to reduce the load on backend services.</p><p>We chose to address this issue by leveraging <a href="https://redis.io/">Redis</a> that can e.g. cache static CMS responses for use in other blocks. While, of course, some static content is still very block-dependant, other is shared — like general config or reusable generic translations — and can be safely cached.</p><p>In our framework, blocks don’t need to implement caching logic themselves; they benefit automatically from the centralized caching system. When multiple blocks on a page require the same underlying data, the first request populates the cache, and subsequent requests are served from the cache without hitting the backend services.</p><h4>Request memoization</h4><p>Next.js 13 and later versions introduced an important performance optimization feature: automatic request memoization. It ensures that identical data fetching requests within the same render pass are actually called only once, significantly reducing unnecessary network calls and improving performance.</p><p>This is especially important for composable apps where the frontend does not define every page, instead relying on a CMS configuration. In such cases, there will be, for example, two identical requests needed for a single page render: one to <a href="https://nextjs.org/docs/app/getting-started/metadata-and-og-images#generated-metadata">generate metadata</a> and the second to actually render page body:</p><pre>export async function generateMetadata({ params }: Props): Promise&lt;Metadata&gt; {<br>    const { locale, slug } = await params;<br>    const { data, meta } = await sdk.modules.getPage({ slug }, locale);<br><br>    return generateSeo({ data, meta });<br>}<br><br>export default async function Page({ params }: Props) {<br>    const { locale, slug } = await params;<br>    const { data } = await sdk.modules.getPage({ slug }, locale);<br><br>    return (<br>        &lt;body&gt;<br>            &lt;Header {...data.header} /&gt;<br>            &lt;PageTemplate slug={slug} data={data} /&gt;<br>            &lt;Footer {...data.footer} /&gt;<br>        &lt;/body&gt;<br>    );<br>}</pre><p>Notice that sdk.modules.getPage({ slug }, locale) is identical in both cases - request memoization will then ensure that it is called only once.</p><p>By default, the native fetch API in Next.js is automatically memoized. This means that if multiple components on the same page make identical fetch requests, Next.js will only execute the actual network request once and reuse the result for all components. This is particularly valuable in our composable architecture, where different blocks might need the same underlying data.</p><pre>// In multiple server components across the page<br>const data = await fetch(&#39;https://api.example.com/data&#39;);<br>const result = await data.json();</pre><p>In the example above, even if this code appears in multiple server components on the same page, the actual network request will only be made once.</p><p>However, it’s important to note that while the native fetch API is supported out of the box, other HTTP client libraries may require additional configuration or adaptations to benefit from Next.js&#39;s memoization capabilities.</p><p>In our implementation, we initially used <a href="https://axios-http.com/">axios</a> for API requests but later switched to <a href="https://github.com/unjs/ofetch">ofetch</a>, which provided a more seamless integration with Next.js’s memoization system while still offering advanced features like interceptors for request/response handling. The transition was quite straightforward and didn’t require too many additional adjustments:</p><pre>// Our SDK implementation using ofetch<br>const ofetchInstance = ofetch.create({<br>    baseURL: apiUrl,<br>    onRequest,<br>    onRequestError,<br>    onResponse,<br>    onResponseError,<br>});<br><br>const makeRequest = &lt;T&gt;(config: CompatRequestConfig): Promise&lt;T&gt; =&gt; {<br>    // Configuration mapping from our standard format to ofetch format<br>    const fetchOptions = {<br>        method: config.method,<br>        query: config.params,<br>        body: config.data,<br>        headers: config.headers,<br>    };<br><br>    return ofetchInstance(config.url, fetchOptions) as Promise&lt;T&gt;;<br>};</pre><p>This approach ensures that API requests are automatically memoized when used in server components, preventing redundant network calls and improving overall application performance without requiring block developers to implement any special logic.</p><h4>Image optimization</h4><p>Images are often the largest assets on a page, so getting them right has an outsized impact on LCP, CLS, and bandwidth. Next.js provides powerful, safe-by-default primitives through <a href="https://nextjs.org/docs/app/api-reference/components/image">Image component</a> that we use across blocks, with a few conventions to keep things fast and stable.</p><p>We always provide width/height or fill to prevent layout shift and enable responsive sizing and lazy loading. Our Image component wraps next/image and only falls back to a plain &lt;img&gt; when dimensions are missing (prefer providing dimensions whenever possible). This is alongside with a default quality=90 that is high enough to not be noticable, but still has a noticeable impact on image weight:</p><pre>export const Image: React.FC&lt;ImageProps&gt; = ({ src, alt = &#39;&#39;, width, height, quality = 90, fill, priority, ...rest }) =&gt; {<br>    if ((width &amp;&amp; height) || fill) {<br>        return (<br>            &lt;NextImage<br>                src={src}<br>                alt={alt}<br>                width={width}<br>                height={height}<br>                quality={quality}<br>                fill={fill}<br>                priority={priority}<br>                fetchPriority={priority ? &#39;high&#39; : &#39;auto&#39;}<br>                {...rest}<br>            /&gt;<br>        );<br>    }<br><br>    return &lt;img src={src as string} alt={alt} /&gt;;<br>};</pre><p>Next.js by default <a href="https://nextjs.org/docs/app/api-reference/components/image#priority">lazy loads images</a>, which is great if they are below-the-fold but should be manually disabled for images that are within the initial viewport, like a hero image. We compute hasPriority only for blocks above the fold and pass it down to images within:</p><pre>export const renderBlocks = async (blocks) =&gt; {<br>    return blocks.map((block, index) =&gt; {<br>        // decides whether the block is above the fold,<br>        // e.g., to disable image lazy loading<br>        const hasPriority = index &lt; 2;<br><br>        return (<br>            &lt;Container key={block.id}&gt;<br>                {renderBlock(block, hasPriority)}<br>            &lt;/Container&gt;<br>        );<br>    });<br>};</pre><p>Keep in mind that this “predictive algorithm”, if it can be called that, is very basic and is prone to being wrong as it does not predict how large the components are. Which means that there can be situations where the third component on the page is still visible, if the first two are quite small.</p><p>This is one of the risks that come from page content being fully dependent on CMS configuration — the code cannot always predict every situation. A better, more foolproof solution would be to define the priority directly in the CMS, where app admins know how the component looks and if it is positioned above-the-fold or not — an improvement that we have in plans for the future.</p><p>Nevertheless, this flag flows into other nested components and ultimately the Image component itself, which also sets the browser fetchPriority accordingly, as shown earlier.</p><p>A good way to save on bandwidth is to set the <a href="https://nextjs.org/docs/app/api-reference/components/image#sizes">sizes prop</a> that matches your CSS breakpoints so the browser downloads the smallest correct candidate.</p><p>For example, for a Hero component with an image that on desktop is always no larger than 50% of the viewport and on mobile is always full width:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94zksSdmTblqcyeLH4b0HA.png" /></figure><p>The sizes prop can be defined accordingly with media queries that match the app&#39;s breakpoints (100vw on smaller screens and 50vw on larger):</p><pre>&lt;Image<br>    src={image.url}<br>    alt={image.alt}<br>    width={image.width}<br>    height={image.height}<br>    priority={hasPriority}<br>    sizes=&quot;(max-width: 64rem): 100vw, 50vw&quot;<br>/&gt;</pre><p>This will generate all the srcset accordingly so that the browser downloads the version that the closely matches the current viewport:</p><pre>&lt;img  alt=&quot;&quot; src=&quot;/_next/image?url=public/hero.png&amp;amp;w=3840&quot;<br>    sizes=&quot;(max-width: 64rem): 100vw, 50vw&quot;<br>    srcset=&quot;<br>        /_next/image?url=public/hero.png&amp;amp;w=384 384w,<br>        /_next/image?url=public/hero.png&amp;amp;w=640 640w,<br>        /_next/image?url=public/hero.png&amp;amp;w=750 750w,<br>        /_next/image?url=public/hero.png&amp;amp;w=828 828w,<br>        /_next/image?url=public/hero.png&amp;amp;w=1080 1080w,<br>        /_next/image?url=public/hero.png&amp;amp;w=1200 1200w,<br>        /_next/image?url=public/hero.png&amp;amp;w=1920 1920w,<br>        /_next/image?url=public/hero.png&amp;amp;w=2048 2048w,<br>        /_next/image?url=public/hero.png&amp;amp;w=3840 3840w<br>    &quot;<br>/&gt;</pre><p>This output is based on <a href="https://nextjs.org/docs/app/api-reference/components/image#devicesizes">deviceSizes config</a> that you can also adjust to your own needs. For example, you might want to narrow down the list of possible viewports if your app is very image-heavy to simply save on the amount of HTML generated:</p><pre>deviceSizes: [430, 828, 1200, 2048, 3840]</pre><p>At the end it’s quite critical to monitor LCP and preloads in Lighthouse and check if it’s possible to adjust the priority if you see that lazy loading:</p><ul><li>does not occur on images below-the-fold</li><li>or it does occur for images above-the-fold</li></ul><h3>Conclusion</h3><p>Building high-performance composable frontends requires addressing challenges across multiple architectural levels. The approach we’ve described combines modular architecture with Next.js server components for efficient rendering, strategic Suspense boundaries for progressive loading, and an API composition layer that optimizes data flow. We further enhance performance through caching, request memoization, and component-level dynamic imports.</p><p>These strategies deliver real benefits: faster page loads, smoother interactions, and responsive applications even under challenging network conditions. For developers, the composable approach improves maintainability, simplifies testing, and allows independent evolution of different application parts.</p><p>As shown in the Lighthouse performance audits, these optimizations result in excellent scores across all Core Web Vitals and performance metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*-o9rI1USZeWav35xH-wIuw.png" /></figure><p>The Open Self Service framework demonstrates this in practice, providing a foundation for building performant composable applications that scale with business needs while delivering exceptional user experiences. This approach is particularly effective in enterprise environments where complex integration requirements, high traffic, and demanding performance standards are common. Open Self Service delivers outstanding results by enabling organizations to build fast, maintainable frontends that seamlessly integrate with multiple backend systems while achieving superior performance metrics.</p><p>Want to see it in action?</p><ul><li><a href="https://www.openselfservice.com/"><strong>Open Self Service website</strong></a></li><li><a href="https://www.openselfservice.com/docs"><strong>Documentation</strong></a></li></ul><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec74b910665" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/ensuring-high-frontend-performance-in-composable-next-js-apps-5ec74b910665">Ensuring high frontend performance in composable Next.js apps</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Experience Platform Starter Kit is here!]]></title>
            <link>https://medium.com/@marcin_krasowski/digital-experience-platform-starter-kit-is-here-7d7f740c9956?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7f740c9956</guid>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[strapi]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[digital-experience]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 10:19:49 GMT</pubDate>
            <atom:updated>2025-09-05T10:19:49.932Z</atom:updated>
            <content:encoded><![CDATA[<h3>Digital Experience Platform Frontend Starter Kit for Next.js is here!</h3><p>We’re excited to announce an initial release of our new <strong>Digital Experience Platform Frontend Starter Kit</strong> built on top of O2S! Kick-start your modern, composable digital platform with our Next.js based starter and built-in CMS integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uczvn_x2FWFkNqlD4ALgg.png" /></figure><h3>What is DXP Starter Kit?</h3><p>The Digital Experience Starter is a frontend starter based on our composable framework architecture, <strong>developed within the Open Self Service project</strong>. It provides a solid foundation for building large-scale solutions, and it is easy to extend and customize, solutions from simple portals to full-fledged digital platforms.</p><p>What makes this kit unique is its flexibility. It allows teams to start quickly with a clean, well-structured frontend and evolve over time, adapting the architecture to meet growing business needs and integrating with additional services as needed.</p><p>Although it can be used in many contexts, the Starter Kit is particularly well-suited for solutions that involve customer interaction and service enablement. Thanks to its modular, headless, and API-first architecture, it’s <strong>easy to evolve the solution toward rich, customer-facing experiences</strong> — without rebuilding from scratch.</p><p>In fact, our long-term development focus is on use cases around customer support and self-service. That’s where the flexibility and composability of the Starter can deliver the most value — enabling fast, scalable, and future-proof digital platforms.</p><p>The framework and this starter reflect everything we’ve learned during real projects. We’ve packaged our best practices into an open-source solution that we’re proud to share with the world today.</p><h3>Architecture</h3><p>The DXP Starter Kit relies on exactly the same architecture that is already <a href="https://www.openselfservice.com/docs/overview/architecture"><strong>utilized in the Open Self Service</strong></a>, with:</p><ul><li>a decoupled Frontend app,</li><li>an intermediate Harmonization server for data aggregation, orchestration and normalization,</li><li>and a UI component library.</li></ul><p>This new starter also is built on top of the <a href="https://www.openselfservice.com/blog/open-self-service-release-1.2.0"><strong>recently released new approach to blocks</strong></a> so you can already start with a more modular way of working.</p><h3>Features</h3><p>The DXP Frontend Starter is designed for building knowledge bases, marketing portals, and Digital Experience Platforms (DXP) of any size. It provides a foundation for content-rich applications that can evolve into comprehensive digital experience solutions. Its features can be extended with Blocks or integrations O2S provides or your own.</p><p>To get a quick overview about what kind of blocks DXP Starter supports, you can now view our newly released <a href="http://storybook-dxp.openselfservice.com/"><strong>Storybook</strong></a> and also a <a href="https://demo-dxp.openselfservice.com/"><strong>demo app</strong></a> that showcases what can be built using our components.</p><p>Take a look at our <a href="https://www.openselfservice.com/docs/app-starters/dxp/overview"><strong>DXP Frontend Starter chapter</strong></a> to learn more about what’s included in this starter.</p><h3>Get started now!</h3><p>To get started, you can use our NPM script to create a new project:</p><pre>npx create-dxp-app@latest my-dxp-portal</pre><p>which, just like in O2S, will create a pre-configured template with all the necessary components, integrations, and best practices to accelerate your development and is ready for your own customizations.</p><p>For more information about installation and requirements, see the <a href="https://www.openselfservice.com/docs/getting-started/installation"><strong>Getting started chapter</strong></a> in our docs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7f740c9956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building composable frontends with Strapi and Next.js]]></title>
            <link>https://medium.com/@marcin_krasowski/building-composable-frontends-with-strapi-and-next-js-3cd3baca11f7?source=rss-46bb1aceab1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cd3baca11f7</guid>
            <category><![CDATA[strapi]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <dc:creator><![CDATA[Marcin Krasowski]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 13:26:06 GMT</pubDate>
            <atom:updated>2025-04-02T09:12:24.626Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re building a frontend-first framework for composable customer portals — <a href="https://www.openselfservice.com/">Open Self Service</a>. To support dynamic content, reusable UI blocks, and flexible layouts, we needed a CMS that gives developers control over structure while staying accessible to business users.</p><p>That’s where Strapi comes in. In O2S, we use it not just for managing page content, but also for defining layout templates, page structures, and component configurations. This approach helps us find the right balance between flexibility for editors and consistency in the frontend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8l7WGQvmv6FyiftwxN_tQ.png" /></figure><p>In this article, we’ll show how Strapi powers the content architecture behind our composable frontend, and how it integrates with Next.js to deliver dynamic pages, structured layouts, and scalable UI patterns.</p><h3>Web content management in modern front-end apps​</h3><p>One of the challenges that often comes with large-scale frontend applications is managing the content in a way that on one hand gives the content editors a large degree of flexibility, and on the other still keeps the app within the bounds of UI/UX rules, standards and branding.</p><p>The solution we are describing in this article follows these principles — it allows composing the pages out of a set of reusable components and templates, while at the same time keeping it under control, without giving complete freedom (which could potentially go against the thought-out UX).</p><p>Of course, our approach may not fully align with the latest trends around visual editors and giving total design freedom, but in our experience, it’s a solid compromise that works well for many real-world use cases.</p><p>To illustrate our approach, throughout the article we will use an exemplary page from our application — the list of invoices. It displays user’s invoices, together with a quick summary of payment balance and history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlCe5wOTquN4FIinaJVK9w.png" /></figure><p>For this page and its components we wanted to give content editors the ability to:</p><ol><li>Decide which components to add to the page.</li><li>Decide how those components should be arranged in the layout.</li><li>And additionally, as our app is constructed of many pages, we also needed to give possibility of managing all pages within the app</li></ol><p>Addressing the requirements needed to be handled in two steps: content modeling and implementation.</p><p>We first focused on appropriate content modeling in Strapi as it seemed to be crucial to further, implementation related, steps.</p><p>If everything was implemented according to the plan, in the CMS we should have control over: page creation, page configuration using templates (like one- or two-column layouts, or some even more complex ones) and page composition using components.</p><h3>Step 1: Content modeling in Strapi<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#step-1-content-modeling-in-strapi">​</a></h3><p>In order to make this kind of content management possible, we tried to reflect the initial ideas and modeled our content based on three types:</p><ul><li>Page that represents any route within the frontend app; we do not model specific pages within the CMS, and instead allow editors to compose the pages they need out of generic types,</li><li>Template that defines the layout of the page and can include simple one- or two-column layouts or more complex ones, and allows the editors to decide where each component should be rendered,</li><li>Block that represents some (smaller or larger) piece of UI that can be placed anywhere in the page layout by the editors.</li></ul><h3>Pages<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#pages">​</a></h3><p>A model for the page is the most important one, as it defines:</p><ul><li>the slug for the page, which is matched against the URL in the browser, and which is a simple localized text field (which means that the page can have different slugs in each language),</li><li>the template for the page that stores the components’ definitions for that page, and which is a dynamic zone where any of the available templates can be picked.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*rOY-nKiHRtahP2qpBdAOzg.png" /></figure><h3>Templates<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#templates">​</a></h3><p>The content type for the templates is quite basic — it is based on a simple system of slots that define some predefined location within the frontend app. The available templates are highly configurable and tailored to UI needs. For simpler pages, a basic two-column layout can be sufficient, consisting of:</p><ul><li>a top slot (that can store e.g. some promotional banners or messages),</li><li>left and right slots for the main content,</li><li>and a bottom slot for some additional content (like FAQs or contact information).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fEwQDSvyk4Eb9LVRZJOL4w.png" /></figure><p>Each slot is a relation field to a Component content type, where multiple instances can be placed (so, in other words, a single slot can accept multiple components):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*c4FrecnqI4LTjRHfvo0Sxg.png" /></figure><h3>Blocks<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#blocks">​</a></h3><p>Before we started modeling the content, we established a few additional requirements that would allow the content editors to work efficiently.</p><p>One of those was to have the possibility to reuse the same components on different pages, without having to maintain duplicates. Having to keep track of, for example, the same generic FAQ for the app that appears on most pages, without having a single instance of it, would be a nightmare — especially as the app grows and expands.</p><p>To solve this issue, we’ve introduced a Block type that represents a single instance of some piece of content. It consists of:</p><ul><li>a name mostly for internal use by the editors to identify each instance, e.g. “FAQ about the tickets” and “FAQ about the invoices”,</li><li>content that’s a dynamic zone into which any of the components can be placed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*MyAZwwQ7g5a9Tc-6bR51Lg.png" /></figure><p>For example, the FAQ component (that uses Strapi’s component type) consists of several text fields, that represent a UI component with title, subtitle, and an accordion with answers to common questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*0X4bdTy4RswfjqCc6ETkqQ.png" /></figure><p>While the FAQ component is quite simple and on the frontend renders only the static content from the CMS, it doesn’t mean that only such components can be defined within Strapi. Another component example is the Invoice List, which on the frontend renders a table with the user’s invoices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*IjGNW7Pw4YNrgpz3KJal5w.png" /></figure><p>This one is a bit more complex — aside from the title, it also handles:</p><ul><li>fields that use a generic component that allowed us to map fields in the API data model to more user-friendly labels, e.g.:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Aliy4WrcQkMc373qy6iwdA.png" /></figure><p>where the keys exactly match the union types in the Invoice model:</p><pre>export class Invoice {<br>  id!: string;<br>  type!: &#39;PAYMENT_COMPLETE&#39; | &#39;PAYMENT_DUE&#39; | &#39;PAYMENT_PAST_DUE&#39;;<br>  paymentStatus!: &#39;STANDARD&#39; | &#39;PROFORMA&#39; | &#39;CREDIT_NOTE&#39; | &#39;DEBIT_NOTE&#39;;<br>  ...<br>}</pre><ul><li>a table that defines which columns should be displayed on the frontend for the invoice table:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LE9ZwOOG6Pl4hRLjd5P-Xw.png" /></figure><h3>App architecture<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#app-architecture">​</a></h3><p>Of course, modeling the content is only part of the solution. We also needed to design the frontend architecture appropriately so that it would allow this type of content management in Strapi, while at the same time being flexible enough.</p><p>We wanted to achieve a fully modular, flexible and highly maintainable solution, so that e.g. the data fetching capability could be used in different frontends/apps or each backend component could be replaced with only small effort.</p><p>This steered us into the composable architecture approach, where different parts can work in a detached way, in a some sort of plug-and-play mode.</p><p>To implement that, we have divided the application into two main components:</p><ul><li>frontend - the frontend app, which is an application that provides the interactive UIs to the customers, composed of reusable UI components and built with <a href="https://nextjs.org/">Next.js</a>,</li><li>api-harmonization - the API Harmonization server, which acts as a backend-for-frontend, where we fetch and aggregate the data from multiple API integrations to fully separate the presentation layer from backend services, built with <a href="https://nestjs.com/">Nest.js</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*WAtqUwC8fqhzbOCCt-bUkw.png" /></figure><p>Each of these applications is semi-independent, therefore they are also built and deployed separately. This also means that the API Harmonization server can even be used without the provided frontend app — using our SDK you can leverage the normalized data model in your own applications.</p><p>It’s also important to understand the overall data flow between each part of the application. On the high level, the frontend app always queries the API harmonization server for content, which in turn fetches data from other external sources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*z92DaR4FZ_bPx_8vgJqHuA.png" /></figure><p>In a bit more details, this flow can be described like this:</p><ol><li>When the user enters a page, a call to the API Harmonization server occurs.</li><li>Firstly, a dedicated Nest.js module handles the request, and other internal services call different APIs, which can range from simple parallel requests to more complex orchestration.</li><li>Received data is normalized and then aggregated into a single response, which usually combines static data from a CMS with dynamic data from different APIs.</li><li>Based on this response, shared parts of the UI are rendered (like navigation or footer), but no other components are rendered yet.</li><li>The page response includes the template that should be used to render the page, together with the IDs of components that should be fetched.</li><li>During rendering, each component queries the API Harmonization server for its own data. This mechanism leverages the <a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming">streaming of server components</a> to make component loading asynchronous while still keeping API requests server-side.</li></ol><h3>Step 2: Implementation<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#step-2-implementation">​</a></h3><p>Since our application is based on composable architecture, the part responsible for the CMS is built in a way that it can be easily replaced with some other integration (with another headless CMS, like Contentful, Storyblok or any other API-based source). Each integration is prepared in the form of npm package, which can be easily swapped with another.</p><p>In this article we will describe only our integration with Strapi, but basically a similar approach could be used when connecting to a different GraphQL-based backend.</p><h3>Getting Strapi content types<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#getting-strapi-content-types">​</a></h3><p>Our first priority was to limit as much as possible the risk of discrepancies between the content model in Strapi and the model in the codebase. The most obvious solution was to always rely on an automatically generated (from GraphQL schema) TypeScript model, that would be then used directly in our code for type safety.</p><p>We achieved this using the <a href="https://the-guild.dev/graphql/codegen/docs/getting-started">graphql-codegen</a>. After installing the main packages:</p><pre>npm install -D graphql @graphql-codegen/cli</pre><p>we have also added a few plugins to make the code generation better suited for our needs (mainly, transforming in into TypeScript):</p><pre>npm install -D  @graphql-codegen/add @graphql-codegen/introspection @graphql-codegen/typescript @graphql-codegen/typescript-graphql-request @graphql-codegen/typescript-operations @graphql-codegen/typescript-resolvers</pre><p>and, lastly, we have also installed <a href="https://www.npmjs.com/package/graphql-request">graphql-request</a> as our GraphQL client:</p><pre>npm i graphql-request</pre><p>With that done, we have prepared a relatively simple config for the codegen that takes care of code generation:</p><pre>import { CodegenConfig } from &#39;@graphql-codegen/cli&#39;;<br><br>const config: CodegenConfig = {<br>  overwrite: true,<br>  schema: `${process.env.CMS_STRAPI_BASE_URL}/graphql`,<br>  documents: &#39;./src/**/*.graphql&#39;,<br>  verbose: true,<br>  generates: {<br>    &#39;generated/strapi.ts&#39;: {<br>      plugins: [<br>        &#39;typescript&#39;,<br>        &#39;typescript-resolvers&#39;,<br>        &#39;typescript-operations&#39;,<br>        &#39;typescript-graphql-request&#39;,<br>        {<br>          add: {<br>            content: &#39;/* eslint-disable */&#39;,<br>          },<br>        },<br>      ],<br>      config: {<br>        skipTypename: true,<br>        rawRequest: true,<br>        maybeValue: &#39;T&#39;,<br>        avoidOptionals: false,<br>      },<br>    },<br>    &#39;./graphql.schema.json&#39;: {<br>      plugins: [&#39;introspection&#39;],<br>    },<br>  },<br>};<br><br>export default config;</pre><p>which relies on:</p><ul><li>CMS_STRAPI_BASE_URL env variable pointing to Strapi server,</li><li>the <a href="https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-graphql-request">typescript-graphql-request plugin</a> that translates GraphQL queries into methods for the <a href="https://www.npmjs.com/package/graphql-request">graphql-request client</a> that is both simple and lightweight, and at the same time powerful enough to fulfill all our requirements (mostly configuring middlewares for logging):</li></ul><pre>this.client = new GraphQLClient(url, {<br>    errorPolicy: &#39;all&#39;,<br>    requestMiddleware: (request) =&gt; {<br>        logger.cmsRequest(request);<br>        return request;<br>    },<br>    responseMiddleware: (response) =&gt; {<br>        if (!(response instanceof Error)) {<br>            logger.cmsResponse(response);<br>        } else {<br>            logger.cmsError(response);<br>        }<br>        return response;<br>    },<br>});</pre><p>Actual requests are kept in separate .graphql files, allowing us to easily leverage all GraphQL features like <a href="https://graphql.org/learn/queries/#fragments">fragments</a>, for example:</p><pre>fagment Page on Page {<br>    slug<br>    locale<br>    template {<br>        __typename<br>        ... on ComponentTemplatesOneColumn {<br>            ...OneColumnTemplate<br>        }<br>        ... on ComponentTemplatesTwoColumn {<br>            ...TwoColumnTemplate<br>        }<br>    }<br>}</pre><p>and</p><pre>fragment TwoColumnTemplate on ComponentTemplatesTwoColumn {<br>    topSlot {<br>        ...Component<br>    }<br>    leftSlot {<br>        ...Component<br>    }<br>    rightSlot {<br>        ...Component<br>    }<br>    bottomSlot {<br>        ...Component<br>    }<br>}</pre><p>which also integrates nicely with some IDEs (like Webstorm) for additional developer experience (navigating between the files, or even testing the queries directly in the editor).</p><p>Now, running the command graphql-codegen will cause a few things to happen:</p><ol><li>GraphQL schema will be downloaded and stored locally (this file is <em>gitignored</em>).</li><li>Codegen will analyze all .graphql files within the ./src folder, and ./generated/strapi.ts file will be generated with:</li></ol><ul><li>all typings that are used within the queries, like:</li></ul><pre>type ComponentTemplatesTwoColumn {<br>    bottomSlot(filters: ComponentFiltersInput, pagination: PaginationArg = {}, sort: [String] = []): [Component]!<br>    ...<br>}</pre><ul><li>and the SDK with methods that reflect each query that was found, like:</li></ul><pre>getPage(<br>    variables: GetPageQueryVariables,<br>    requestHeaders?: GraphQLClientRequestHeaders,<br>): Promise&lt;{<br>    data: GetPageQuery;<br>    errors?: GraphQLError[];<br>    extensions?: any;<br>    headers: Headers;<br>    status: number;<br>}&gt; {<br>    ...<br>},</pre><h3>Creating GraphQL queries<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#creating-graphql-queries">​</a></h3><p>For each of the content types mentioned earlier we have prepared appropriate GraphQL code — divided into fragments (blocks, templates and other models) and queries (for fetching pages and other non-block items like header or footer):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*aqqpsU6UNz2p3PmSkyd2tg.png" /></figure><p>The requests themselves are quite straightforward, and simply focus on getting the content from the CMS (while using fragments to make the queries reusable):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ooaUI0NC9f1JGNFwwybSA.png" /></figure><p>There are too many queries to list here, but you can always take a look at <a href="https://github.com/o2sdev/openselfservice/tree/main/packages/integrations/strapi-cms/src/modules/cms/graphql">our open-source repository</a> for more examples.</p><p>Data fetching happens through NestJS, where we’ve introduced a dedicated service for CMS content that exposes methods for each CMS block:</p><pre>export class CmsService implements CMS.Service {<br>    constructor(private readonly graphqlService: GraphqlService) {}<br><br>    private getBlock = (options: CMS.Request.GetCmsEntryParams) =&gt; {<br>        const component = this.graphqlService.getComponent({<br>            id: options.id,<br>            locale: options.locale,<br>        });<br><br>        return forkJoin([component]).pipe(<br>            map(([component]) =&gt; {<br>                if (!component?.data.component) {<br>                    throw new NotFoundException();<br>                }<br>                return component.data;<br>            }),<br>        );<br>    };<br><br>    getFaqBlock(options: CMS.Request.GetCmsEntryParams) {<br>        return this.getBlock(options).pipe(map(mapFaqBlock));<br>    }<br><br>    getInvoiceListBlock(options: CMS.Request.GetCmsEntryParams) {<br>        return this.getBlock(options).pipe(map(mapInvoiceListBlock));<br>    }<br>}</pre><p>where graphqlService.getComponent is a generated method that makes a GraphQL query for the <em>Component</em> content type:</p><pre>fragment Component on Component {<br>    __typename<br>    documentId<br>    content {<br>        __typename<br>    }<br>}</pre><h3>Data aggregation<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#data-aggregation">​</a></h3><p>One of our core principles is to minimize the amount of data logic (like orchestration) on the frontend. It should focus mostly on rendering the content and handling user interactions, not on deciding which backend API to use to display pages.</p><p>We achieve that using a separate set of modules within the NestJS app that handle exactly that: data orchestration and aggregation. This is the place where we call the methods to:</p><ul><li>fetch the content from the CMS,</li><li>get or post backed data (like user invoices or tickets).</li></ul><pre>export class InvoiceListService {<br>  constructor(<br>    private readonly cmsService: CMS.Service,<br>    private readonly invoiceService: Invoices.Service,<br>  ) {}<br><br>  getInvoiceListBlock(<br>      query: GetInvoiceListBlockQuery,<br>      headers: AppHeaders<br>  ): Observable&lt;InvoiceListBlock&gt; {<br>    const cms = this.cmsService.getInvoiceListBlock({ <br>        ...query,<br>        locale: headers[&#39;x-locale&#39;] <br>    });<br><br>    return forkJoin([cms]).pipe(<br>      concatMap(([cms]) =&gt; {<br>        return this.invoiceService<br>          .getInvoiceList({<br>            ...query,<br>            limit: cms.pagination?.limit || query.limit,<br>          })<br>          .pipe(map((invoices) =&gt; mapInvoiceList(<br>              invoices, <br>              cms, <br>              headers[&#39;x-locale&#39;]<br>          )));<br>      }),<br>    );<br>  }<br>}</pre><p>This allows us to easily orchestrate operations — like in the example above, use CMS configuration to fetch the initial number of user invoices. Of course, that’s one of the simplest cases, and often this may require calling several different APIs in order to compose a single response.</p><p>Once all necessary data is fetched, we aggregate and transform it into a format that will be easy to use on the frontend, like combining enum values with user-friendly labels:</p><pre>export const mapInvoice = (<br>  invoice: Invoices.Model.Invoice,<br>  cms: CMS.Model.InvoiceListBlock.InvoiceListBlock,<br>  locale: string,<br>): Invoice =&gt; {<br>  return {<br>    id: invoice.id,<br>    currency: invoice.currency,<br>    type: {<br>      displayValue: cms.fieldMapping.type?.[invoice.type],<br>    },<br>    paymentStatus: {<br>      displayValue: cms.fieldMapping.paymentStatus?.[invoice.paymentStatus],<br>      value: invoice.paymentStatus,<br>    },<br>    totalAmountDue: checkNegativeValue(invoice.totalAmountDue),<br>    amountToPay: checkNegativeValue(invoice.totalToBePaid),<br>    paymentDueDate: {<br>      displayValue: Date.formatDateRelative(<br>        invoice.paymentDueDate,<br>        locale,<br>        cms.labels.today,<br>        cms.labels.yesterday,<br>      ),<br>      value: invoice.paymentDueDate,<br>    },<br>  };<br>};</pre><p>where e.g. paymentStatus field contains both the text that is rendered (fetched from Strapi), and original enum value (fetched from backend API), and can look like this:</p><pre>&quot;paymentStatus&quot;: {<br>  &quot;displayValue&quot;: &quot;Past Due&quot;,<br>  &quot;value&quot;: &quot;PAYMENT_PAST_DUE&quot;<br>}</pre><p>This kind of aggregation makes rendering the content on the frontend often trivial, as all the necessary data is right there, without having to worry about accessing the labels and values separately, from different APIs or different objects.</p><h3>Rendering the content<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#rendering-the-content">​</a></h3><p>Finally, on the frontend we use Next.js with App Router to render the pages.</p><p>Since in Strapi we modeled our pages as a generic <em>Page</em> type, then in the frontend app we also do not have any pre-configured routes and instead rely on the catch-all route that intercepts all incoming traffic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*g7HkpnyAlXII02c91lNTDg.png" /></figure><p>Within that route we firstly fetch the general page data (like title, SEO metadata), together with the information about which template that page uses and a list of components within that template:</p><pre>export default async function Page({ params }: Props) {<br>  const session = await auth();<br><br>  if (!session?.user) return signIn();<br><br>  const { locale, slug } = await params;<br><br>  try {<br>    const { data, meta } = await sdk.modules.getPage(<br>      slug,<br>      locale,<br>      session.accessToken<br>    );<br><br>    if (!data || !meta) {<br>      notFound();<br>    }<br><br>    return (<br>      &lt;main&gt;<br>        &lt;PageTemplate slug={slug} data={data} session={session} /&gt;<br>      &lt;/main&gt;<br>    );<br>  } catch (error) {<br>    notFound();<br>  }<br>}</pre><p>Then, after we check which template needs to be used, we render the blocks in each of its slots, while at the same time configuring the layout:</p><pre>export const TwoColumnTemplate = ({ slug, data, session }: TwoColumnTemplateProps) =&gt; {<br>  return (<br>    &lt;div className=&quot;flex flex-col gap-8&quot;&gt;<br>      &lt;div className=&quot;flex flex-col gap-8&quot;&gt;<br>        {renderBlocks(data.slots.top, slug, session.accessToken)}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;grid grid-cols-1 lg:grid-cols-2&quot;&gt;<br>        &lt;div className=&quot;flex flex-col gap-8&quot;&gt;<br>          {renderBlocks(data.slots.left, slug, session.accessToken)}<br>        &lt;/div&gt;<br><br>        &lt;div className=&quot;flex flex-col gap-8&quot;&gt;<br>          {renderBlocks(data.slots.right, slug, session.accessToken)}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;flex flex-col gap-8&quot;&gt;<br>        {renderBlocks(data.slots.bottom, slug, session.accessToken)}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>We also need to figure out what to actually render, as each slot contains a simple array of blocks’ definitions:</p><pre>&quot;bottom&quot;: [<br>  { &quot;__typename&quot;: &quot;InvoiceListBlock&quot;, &quot;id&quot;: &quot;invoice-list-1&quot; },<br>  { &quot;__typename&quot;: &quot;FaqBlock&quot;, &quot;id&quot;: &quot;faq-1&quot; }<br>]</pre><p>We do that with a simple switch that looks at the block name and then just return the appropriate component:</p><pre>export const renderBlocks = (<br>    blocks: CMS.Model.Page.SlotBlock[], <br>    slug: string[], <br>    accessToken: string<br>) =&gt; {<br>  return blocks.map((block) =&gt; {<br>    switch (block.__typename as Modules.Page.Model.Blocks) {<br>      case &#39;FaqBlock&#39;:<br>        return &lt;Faq key={block.id} id={block.id} accessToken={accessToken} /&gt;;<br>      case &#39;InvoiceListBlock&#39;:<br>        return &lt;InvoiceList key={block.id} id={block.id} accessToken={accessToken} /&gt;;<br>      ...<br>    }<br>  });<br>};</pre><p>Finally, the actual rendering of blocks happens using the React Server Components. Each block fetches its own data:</p><pre>export const InvoiceList = async ({ id, accessToken, locale }: InvoiceListProps) =&gt; {<br>  const data = await sdk.blocks.getInvoiceList(<br>    { id },<br>    { &#39;x-locale&#39;: locale },<br>    accessToken,<br>  );<br><br>  return (<br>    &lt;Suspense key={id} fallback={&lt;Loading bars={20} /&gt;}&gt;<br>      &lt;InvoiceListClient {...data} id={id} accessToken={accessToken} locale={locale} /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>};</pre><p>This approach has several advantages:</p><ul><li>it makes blocks more independent and decouples them from the Page model,</li><li>utilizes server-side capabilities of Next.js for server components, with HTML streaming and loading states using Suspense,</li><li>makes it possible, in the future, to extract those blocks out of the frontend app itself, and transform them into standalone micro-frontend applications.</li></ul><p>The biggest drawback, however, is that each block produces its own HTTP request for its data. Although this happens server-side, so we are not limited by the browsers (and their limits on simultaneous requests) this can still potentially cause overfetching in some cases — if there would be several blocks on one page that fetch exactly the same data from some backend API, this also results in several API calls, even if they are exactly the same.</p><p>Thankfully, this can be mitigated by using cache on two levels:</p><ol><li>Leveraging <a href="https://nextjs.org/docs/app/building-your-application/caching#request-memoization">request memoization</a> provided by Next.js, which ensures that the same fetching function is called only once during rendering, preventing multiple calls to Nest.js for the same data.</li><li>Introducing cache to the Nest.js application (e.g. via <a href="https://redis.io/">Redis</a>) for:</li></ol><ul><li>user data, which should be cached only for a very short time (to cover a single page render) as in most cases it can be very dynamic,</li><li>CMS content, which can be cached for longer as usually it does not change that often.</li></ul><p>In our application we have introduced both ways, using memoization on the frontend and caching the content fetched from Strapi in Redis, and have plans for improving performance even further by also caching user data in the future.</p><p>Lastly, we do actual rendering within the client component, where we render JSX, keep local component state if necessary, and handle all user interactions:</p><pre>&#39;use client&#39;;<br><br>export const InvoiceListClient = ({ ...component }: InvoiceListClientProps) =&gt; {<br>  const initialFilters = {};<br><br>  const [data, setData] = useState(component);<br>  const [filters, setFilters] = useState(initialFilters);<br><br>  const handleFilter = async (newFilters) =&gt; {<br>    const newData = await sdk.components.getInvoiceList(newFilters);<br>    setData(newData);<br>  };<br><br>  const handleReset = async () =&gt; {<br>    const newData = await sdk.components.getInvoiceList(initialFilters);<br>    setFilters(initialFilters);<br>    setData(newData);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;Filters onSubmit={handleFilter} onReset={handleReset} /&gt;<br><br>        &lt;Table&gt;{data}&lt;/Table&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Result<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#result">​</a></h3><p>While it may seem complex, this kind of approach successfully integrates Strapi with frontend to power dynamic, API-driven applications. This enables an effective collaboration platform between developers and content editors by providing flexibility and empowering non-technical users to manage data without having to change the source code each time there is a need to create or modify a page composed of UI blocks.</p><p>Our solution includes:</p><ul><li>Modular and decoupled page templates with reusable components, making it easy to define layouts and populate content dynamically.</li><li>Server-side rendering of blocks using Next.js server components, enabling better performance with HTML streaming and Suspense for loading states.</li><li>A scalable approach to data fetching by encapsulating fetch logic within individual components, making them independent and reusable.</li><li>Frontend request memoization paired with backend Redis caching to optimize API calls, reduce overfetching, and improve overall performance.</li></ul><p>This architecture not only supports content-driven apps but also other heavily API-powered frontend solutions. It combines ease of maintenance with scalability and extensibility, ensuring both developers and content editors can work effectively.</p><h3>Conclusion<a href="http://localhost:3006/blog/building-composable-frontends-with-strapi-and-nextjs#conclusion">​</a></h3><p>The integration of Strapi with Open Self Service shows that content management with a headless CMS doesn’t have to stop at landing pages or blog posts. With the right content model structure and implementation in the frontend app, it can support complex cases.</p><p>In our case Strapi was used to:</p><ul><li>Model page templates and components</li><li>Manage dynamic data presentation</li><li>Reuse content blocks across the app</li><li>Empower non-technical users to make changes without code</li></ul><p>Combined with the composable architecture of O2S, this gives us a powerful foundation to build modern customer-facing portals that are scalable, flexible, and easy to maintain.</p><p>Want to see it in action?</p><ul><li><a href="https://www.openselfservice.com/">Open Self Service website</a></li><li><a href="https://www.openselfservice.com/docs">Documentation</a></li><li><a href="https://github.com/o2sdev/openselfservice">GitHub repo</a></li></ul><p>We’d love your feedback — or even better, your contributions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cd3baca11f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>