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

add deferred & critical data pattern #53

Merged
merged 1 commit into from
Jun 11, 2024
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
70 changes: 51 additions & 19 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,37 +70,69 @@ export const links: LinksFunction = () => {
];
};

export async function loader({request, context}: LoaderFunctionArgs) {
const {storefront, cart, env} = context;
const layout = await getLayoutData(context);
const isLoggedInPromise = context.customerAccount.isLoggedIn();
export async function loader(args: LoaderFunctionArgs) {
// Start fetching non-critical data without blocking time to first byte
const deferredData = loadDeferredData(args);

const seo = seoPayload.root({shop: layout.shop, url: request.url});
// Await the critical data required to render initial state of the page
const criticalData = await loadCriticalData(args);

return defer(
{
shop: getShopAnalytics({
storefront: context.storefront,
publicStorefrontId: env.PUBLIC_STOREFRONT_ID,
}),
consent: {
checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN,
storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN,
},
isLoggedIn: isLoggedInPromise,
layout,
selectedLocale: storefront.i18n,
cart: cart.get(),
seo,
...deferredData,
...criticalData,
},
{
headers: {
'Set-Cookie': await context.session.commit(),
'Set-Cookie': await args.context.session.commit(),
},
},
);
}

/**
* Load data necessary for rendering content above the fold. This is the critical data
* needed to render the page. If it's unavailable, the whole page should 400 or 500 error.
*/
async function loadCriticalData({request, context}: LoaderFunctionArgs) {
const [layout] = await Promise.all([
getLayoutData(context),
// Add other queries here, so that they are loaded in parallel
]);

const seo = seoPayload.root({shop: layout.shop, url: request.url});

const {storefront, env} = context;

return {
layout,
seo,
shop: getShopAnalytics({
storefront,
publicStorefrontId: env.PUBLIC_STOREFRONT_ID,
}),
consent: {
checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN,
storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN,
},
selectedLocale: storefront.i18n,
};
}

/**
* Load data for rendering content below the fold. This data is deferred and will be
* fetched after the initial page load. If it's unavailable, the page should still 200.
* Make sure to not throw any errors here, as it will cause the page to 500.
*/
function loadDeferredData({context}: LoaderFunctionArgs) {
const {cart, customerAccount} = context;

return {
isLoggedIn: customerAccount.isLoggedIn(),
cart: cart.get(),
};
}

export const meta = ({data}: MetaArgs<typeof loader>) => {
return getSeoMeta(data!.seo as SeoConfig);
};
Expand Down
153 changes: 112 additions & 41 deletions app/routes/($locale)._index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

export const headers = routeHeaders;

export async function loader({params, context}: LoaderFunctionArgs) {
export async function loader(args: LoaderFunctionArgs) {
const {params, context} = args;
const {language, country} = context.storefront.i18n;

if (
Expand All @@ -29,53 +30,107 @@
throw new Response(null, {status: 404});
}

const {shop, hero} = await context.storefront.query(HOMEPAGE_SEO_QUERY, {
variables: {handle: 'freestyle'},
});
// Start fetching non-critical data without blocking time to first byte
const deferredData = loadDeferredData(args);

const seo = seoPayload.home();
// Await the critical data required to render initial state of the page
const criticalData = await loadCriticalData(args);

return defer({
return defer({...deferredData, ...criticalData});
}

/**
* Load data necessary for rendering content above the fold. This is the critical data
* needed to render the page. If it's unavailable, the whole page should 400 or 500 error.
*/
async function loadCriticalData({context}: LoaderFunctionArgs) {
const [{shop, hero}] = await Promise.all([
context.storefront.query(HOMEPAGE_SEO_QUERY, {
variables: {handle: 'freestyle'},
}),
// Add other queries here, so that they are loaded in parallel
]);

return {
shop,
primaryHero: hero,
// These different queries are separated to illustrate how 3rd party content
// fetching can be optimized for both above and below the fold.
featuredProducts: context.storefront.query(
HOMEPAGE_FEATURED_PRODUCTS_QUERY,
{
variables: {
/**
* Country and language properties are automatically injected
* into all queries. Passing them is unnecessary unless you
* want to override them from the following default:
*/
country,
language,
},
seo: seoPayload.home(),
};
}

/**
* Load data for rendering content below the fold. This data is deferred and will be
* fetched after the initial page load. If it's unavailable, the page should still 200.
* Make sure to not throw any errors here, as it will cause the page to 500.
*/
function loadDeferredData({context}: LoaderFunctionArgs) {
const {language, country} = context.storefront.i18n;

const featuredProducts = context.storefront
.query(HOMEPAGE_FEATURED_PRODUCTS_QUERY, {
variables: {
/**
* Country and language properties are automatically injected
* into all queries. Passing them is unnecessary unless you
* want to override them from the following default:
*/
country,
language,
},
),
secondaryHero: context.storefront.query(COLLECTION_HERO_QUERY, {
})
.catch((error) => {
// Log query errors, but don't throw them so the page can still render
console.error(error);

Check warning on line 83 in app/routes/($locale)._index.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Unexpected console statement
return null;
});

const secondaryHero = context.storefront
.query(COLLECTION_HERO_QUERY, {
variables: {
handle: 'backcountry',
country,
language,
},
}),
featuredCollections: context.storefront.query(FEATURED_COLLECTIONS_QUERY, {
})
.catch((error) => {
// Log query errors, but don't throw them so the page can still render
console.error(error);

Check warning on line 97 in app/routes/($locale)._index.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Unexpected console statement
return null;
});

const featuredCollections = context.storefront
.query(FEATURED_COLLECTIONS_QUERY, {
variables: {
country,
language,
},
}),
tertiaryHero: context.storefront.query(COLLECTION_HERO_QUERY, {
})
.catch((error) => {
// Log query errors, but don't throw them so the page can still render
console.error(error);

Check warning on line 110 in app/routes/($locale)._index.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Unexpected console statement
return null;
});

const tertiaryHero = context.storefront
.query(COLLECTION_HERO_QUERY, {
variables: {
handle: 'winter-2022',
country,
language,
},
}),
seo,
});
})
.catch((error) => {
// Log query errors, but don't throw them so the page can still render
console.error(error);

Check warning on line 124 in app/routes/($locale)._index.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Unexpected console statement
return null;
});

return {
featuredProducts,
secondaryHero,
featuredCollections,
tertiaryHero,
};
}

export const meta = ({matches}: MetaArgs<typeof loader>) => {
Expand Down Expand Up @@ -103,11 +158,17 @@
{featuredProducts && (
<Suspense>
<Await resolve={featuredProducts}>
{({products}) => {
if (!products?.nodes) return <></>;
{(response) => {
if (
!response ||
!response?.products ||
!response?.products?.nodes
) {
return <></>;
}
return (
<ProductSwimlane
products={products}
products={response.products}
title="Featured Products"
count={4}
/>
Expand All @@ -120,9 +181,11 @@
{secondaryHero && (
<Suspense fallback={<Hero {...skeletons[1]} />}>
<Await resolve={secondaryHero}>
{({hero}) => {
if (!hero) return <></>;
return <Hero {...hero} />;
{(response) => {
if (!response || !response?.hero) {
return <></>;
}
return <Hero {...response.hero} />;
}}
</Await>
</Suspense>
Expand All @@ -131,11 +194,17 @@
{featuredCollections && (
<Suspense>
<Await resolve={featuredCollections}>
{({collections}) => {
if (!collections?.nodes) return <></>;
{(response) => {
if (
!response ||
!response?.collections ||
!response?.collections?.nodes
) {
return <></>;
}
return (
<FeaturedCollections
collections={collections}
collections={response.collections}
title="Collections"
/>
);
Expand All @@ -147,9 +216,11 @@
{tertiaryHero && (
<Suspense fallback={<Hero {...skeletons[2]} />}>
<Await resolve={tertiaryHero}>
{({hero}) => {
if (!hero) return <></>;
return <Hero {...hero} />;
{(response) => {
if (!response || !response?.hero) {
return <></>;
}
return <Hero {...response.hero} />;
}}
</Await>
</Suspense>
Expand Down
Loading
Loading