-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Docs: Add best practices collection and data fetching guide #7376
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
125
docs/content/guides/6.best-practices/2.data-fetching.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_: | ||
mateuszo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
- **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 | ||
mateuszo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
### 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 | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.