Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: Add best practices collection and data fetching guide #7376

Merged
merged 3 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/content/guides/1.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ If you have any questions or need help with anything, please don't hesitate to g
#section-3
:card{to="/guides/customization-next-js" title="Customization" description="Alokai is not a cookie-cutter solution, it is meant to be able to handle even the most complex use cases. This guide will take you through the most common customization scenarios." icon="tabler:tool"}

#section-4
:card{to="/guides/kubernetes-probe" title="Kubernetes Probes" description="Alokai Cloud customers' middleware and frontend apps are deployed in Kubernetes. Check how Kubernetes mechanisms are used by Alokai Cloud" icon="tabler:heart-rate-monitor"}

#section-5
:card{to="/guides/best-practices" title="Best Practices" description="Check what to follow to keep your storefront in the best possible shape" icon="tabler:rosette-discount-check"}


::


Expand Down
5 changes: 5 additions & 0 deletions docs/content/guides/6.best-practices/1.index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Best Practices

In this guide, we have compiled a collection of best practices to help you optimize your development workflow, improve code quality, and ensure maintainability.

::card{title="Data Fetching" icon="tabler:mobiledata" to="/guides/best-practices/data-fetching" }
125 changes: 125 additions & 0 deletions docs/content/guides/6.best-practices/2.data-fetching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Data Fetching best practices

Data fetching is a critical aspect of web application performance. While Alokai leverages established best practices from frameworks like Next.js and Nuxt, this guide explains how to effectively implement these strategies in the context of Alokai's architecture.

Read about data fetching in general in Next.js / Nuxt official documentation:

- [Data fetching in Next.js](https://nextjs.org/docs/app/building-your-application/data-fetching)
- [Data fetching in Nuxt](https://nuxt.com/docs/getting-started/data-fetching)

## Data fetching strategies

There are three data-fetching strategies:

- **Client-Side Fetching:** Data is fetched by the client (usually a browser) directly from an API.
- **Server-Side Fetching / Server-Side Rendering (SSR):** Data is fetched on the server during the request and delivered to the client as pre-rendered HTML.
- **Static Site Generation (SSG):** Pages are pre-rendered at build time, suitable for content that doesn't change frequently. E-commerce applications are highly dynamic, so we’re not covering this strategy as it’s rarely used in this context. Cached server-side rendered pages are a good replacement for SSG.

The diagram helps to visualize the two first strategies:

<img src="/images/data-fetching-strategies.svg" alt="data fetching strategies" class="mx-auto">

The `Storefront` is a Next/Nuxt application. Api is any 3rd party system.

Animation below visualizes the difference between server and client side fetching. Product data is fetched on the server and rendered to HTML, so the product data is visible immediately after page load. Cart data is fetched client side, so we see a spinner that is replaced by content when cart data is loaded.

<img src="/images/ssr-csr.gif" alt="data fetching animation" class="mx-auto">

## How to pick data fetching strategy

The rule of thumb is: _always use server-side fetching except for_:

- **lazy loaded data** - data that is not visible immediately on page load and can be removed from server-side rendered html to reduce its size. For example:
- product reviews should appear only when user clicks expand on the “reviews accordion”
- content below the fold is fetched on scroll

- **personalized data** - data that is different for each user or group. Fetching such data server side would not only cause flickering but also might cause problem with caching ([read more about caching](/storefront/features/cdn/making-ssr-cacheable)). For example:
- pricing data might be different for each customer group
- product recommendations are based on individual user’s journey
- cart content is specific for each user

## Data fetching in Alokai

Alokai architecture introduces the Middleware in between the front-end application and the APIs. This adds two additional possible routes to our diagram, but most of the traffic should go through the middleware, because:

- it is cached on the CDN
- it keeps your architecture simple
- you can easily monitor middleware traffic in the console
- enables [data federation](/middleware/guides/federation)
- ensures middleware reusability and omnichannel capabilities

<img src="/images/data-fetching-alokai-strategies.svg" alt="data fetching strategies with alokai" class="mx-auto">

Fortunately, we can reject the route between the server and the API, because:

- effectively it is similar to reaching through the middleware, but adds unnecessary complexity to the architecture,
- tightly couples the storefront with the API.

The direct route between the browser and API should be avoided, because it:

- tightly couples storefront with the API,
- reduces performance by bypasses CDN cache.

Use direct direct browser to API calls only when communicating via middleware is not possible or requires unnecessary effort. Sample scenarios when it might be valid to communicate directly between client and API:

- the communication requires extremely low latency - e.g. voice or video stream
- communication with API is done via some SDK that requires direct client (browser) interaction - e.g. analytics or authentication services

## CDN Caching

To further improve your application performance we encourage you to enable the CDN. The CDN is capable of caching responses from the server and the middleware to the browser.

<img src="/images/data-fetching-cdn.svg" alt="data fetching and CDN" class="mx-auto">

::info
[Read more about caching here.](/storefront/features/cdn/making-ssr-cacheable)
::

## Examples

### Server-Side fetching in Next.js

In this example we fetch product data on the server and display it's name.

```tsx
import { getSdk } from '@/sdk';

export default async function ServerSideDataFetching() {
const sdk = getSdk(); // get the SDK instance on the server side.

const response = await sdk.unified.getProductDetails({ id: '300013358' }); // fetch product data
const product = response?.product ?? null;

return <h1>Product name: {product.name}</h1>; // display product name
}
```

### Client-side fetching in Next.js

In this example we fetch product data on the client. We display loader while data is being fetched. Tanstack query is used to fetch data and manage component state.

```tsx
'use client'; // tell nextjs to render this component on the client side

import { SfLoaderCircular } from '@storefront-ui/react';
import { useQuery } from '@tanstack/react-query';

import { useSdk } from '@/sdk/alokai-context';

export default function ClientSideDataFetching() {
const sdk = useSdk(); // get the SDK instance on the client side.

// use tanstack query to fetch product data and manage the loading state
const { data: productData, isLoading } = useQuery({
queryFn: () => sdk.unified.getProductDetails({ id: '300013358' }),
queryKey: ['product'],
});

// display a loader while product data is loading
if (isLoading || !productData) {
return <SfLoaderCircular />;
}

return <h1>Product name: {productData.product.name}</h1>; // display product name
}
```
5 changes: 5 additions & 0 deletions docs/content/guides/6.best-practices/_dir.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
title: Best Practices
sidebarRoot: true
navigation:
icon: tabler:rosette-discount-check

Loading
Loading