Skip to content

feat: loads first page product gallery from Build Time (getStaticProps) + improve number of requests (+) - #2721

Merged
eduardoformiga merged 15 commits into
mainfrom
feat/SFS-1883-load-productGallery-ssr
Mar 31, 2025
Merged

eduardoformiga merged 15 commits into
mainfrom
feat/SFS-1883-load-productGallery-ssr

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Mar 12, 2025 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

This PR aims to fetch the first page from the PLPs using the server side. This can improve SEO and performance.

It uses the same variables that are used in the first fetch from the client side. If the values have changed 5 minutes from the build or from the latest fetch of the first page, we refetch the first page and update the values.

It also improves:

  • The cache mechanism from PLPs (deepEquals instead of stringify (and ===)).
  • The URL params updates (fuzzy and operator) - there is no longer a need to refetch to add these params.
  • Decrease the number of requests made on the Client Side in the first render (6 to 4).
  • The cache and refresh logic for the first page.

How to test it?

You can run locally:
I recommend to set the cache to 1 minute to test the requests from PLP here:

you can also test it in the preview link:
https://starter-7w8gjvlea-vtex.vercel.app/office

Observe the requests from the PLP:

Starters Deploy Preview

PR

Preview:

https://starter-mrmhyx2h3-vtex.vercel.app/office

@eduardoformiga
eduardoformiga requested a review from a team as a code owner March 12, 2025 01:15
@eduardoformiga
eduardoformiga requested review from emersonlaurentino and pedromtec and removed request for a team March 12, 2025 01:15
@codesandbox-ci

codesandbox-ci Bot commented Mar 12, 2025 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@eduardoformiga eduardoformiga changed the title feat: Loads first page product gallery from SSR feat: loads first page product gallery from SSR + improve number of requests (+) Mar 12, 2025
Comment on lines +57 to +60
const applySearchState = useApplySearchState()
useEffect(() => {
applySearchState(formatSearchState(state))
}, [])

@eduardoformiga eduardoformiga Mar 12, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updates the URL with the search State, which already started with fuzzy and operator from the server side. We don't need to refetch anymore (less 1 request).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finally!!! That's huge 🚀

Comment on lines +41 to +51
const selectedFacets = [
...collection?.meta.selectedFacets,
{
key: 'fuzzy',
value: serverData?.search?.metadata?.fuzzy ?? 'auto',
},
{
key: 'operator',
value: serverData?.search?.metadata?.logicalOperator ?? 'and',
},
]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

init facets also with the fuzzy and operator

Comment on lines +146 to +153
const [serverManyProductsData, serverManyProductsVariables] =
await fetchServerManyProducts({
itemsPerPage: cmsPage?.settings?.productGallery?.itemsPerPage,
sort: cmsPage?.settings?.productGallery
?.sortBySelection as SearchState['sort'],
term: '',
selectedFacets: data?.collection?.meta.selectedFacets,
})

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fetch products from SSR, also uses serverManyProductsVariables for cache mechanism.

Comment on lines +180 to +184
data: {
...data,
...serverManyProductsData,
},
serverManyProductsVariables,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pass the fetch result to the front.

Comment on lines +81 to +90
const initialPages = params?.initialPages?.search ? [params.initialPages] : []
const initialVariables = params?.serverManyProductsVariables
? [getKey(params.serverManyProductsVariables)]
: []

const [pages, setPages] =
useState<ClientManyProductsQueryQuery[]>(initialPages)
// We create pagesRef as a mirror of the pages state so we don't have to add pages as a dependency of the useGalleryPage hook
const pagesRef = useRef<ClientManyProductsQueryQuery[]>([])
const pagesCache = useRef<string[]>([])
const pagesRef = useRef<ClientManyProductsQueryQuery[]>(initialPages)
const pagesCache = useRef<string[]>(initialVariables)

@eduardoformiga eduardoformiga Mar 12, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we started the pages and the cache from PLPs with the values from server in page 0

Comment on lines +106 to +109
const hasSameVariables = deepEquals(
pagesCache.current[page],
getKey(localizedVariables)
)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

improves request/cache/refetch mechanism.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: @eduardoformiga do you have metrics for both comparison strategies that favor deepEquals here?

Comment on lines +111 to +116
const shouldFetchFirstPage = useShouldFetchFirstPage({
page,
generatedBuildTime,
})

const shouldFetch = !hasSameVariables || shouldFetchFirstPage

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First page cache mechanism.

Comment on lines -115 to -139
// If there is no fuzzy or operator facet, we need to add them to the selectedFacets and re-fetch the query
const shouldRefetchQuery =
!queryResult.error && (!fuzzyFacetValue || !operatorFacetValue)

if (shouldRefetchQuery) {
if (queryResult.data) {
setState({
...state,
selectedFacets: [
...selectedFacets,
{
key: 'fuzzy',
value: queryResult.data.search.metadata?.fuzzy ?? 'auto',
},
{
key: 'operator',
value: queryResult.data.search.metadata?.logicalOperator ?? 'and',
},
],
// Update the Search state (and URL) only if the values from fuzzy and operator changes
updateSearchParamsState({
selectedFacets,
updatedFuzzyFacetValue,
updatedOperatorFacetValue,
setState,
state,
})
}

// The first result is not relevant, return null data to avoid rendering the page while the query is being re-fetched
return { ...queryResult, isValidating: true, data: null }
}

@eduardoformiga eduardoformiga Mar 12, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is no refetch to include facets values in the URL (-1 request)

Comment on lines +178 to +183
updateSearchParamsState({
selectedFacets,
updatedFuzzyFacetValue,
updatedOperatorFacetValue,
setState,
state,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we just update the URL and Search State if the values from fuzzy and operator change.

Comment on lines +17 to +27
/**
* This hook determine if the first page (page 0) should be fetched.
* This is because the first page is initially fetched from the Server Side, and injected in the cache (for Performance and SEO).
* So this hook checks if the first page should be fetched again in the Client Side
* after 5 minutes since the build time (last fetch from Server Side) or the last fetched time from the ClientSide.
*
* @param page The page number
* @param generatedBuildTime The time the page was generated
* @returns boolean
*
**/

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀

@eduardoformiga eduardoformiga changed the title feat: loads first page product gallery from SSR + improve number of requests (+) feat: loads first page product gallery from Build Time (getStaticProps) + improve number of requests (+) Mar 17, 2025

@lucasfp13 lucasfp13 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great improvements 🚀

Comment on lines +106 to +109
const hasSameVariables = deepEquals(
pagesCache.current[page],
getKey(localizedVariables)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: @eduardoformiga do you have metrics for both comparison strategies that favor deepEquals here?

Comment thread pnpm-lock.yaml

@lucasfp13 lucasfp13 Mar 24, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎗️ suggestion: This is one of the cases Biome didn't ignore the automatic lint and fix, please rebase with main to solve it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done here

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After some fight, now it worked. hahaha

@eduardoformiga

Copy link
Copy Markdown
Member Author

question: @eduardoformiga do you have metrics for both comparison strategies that favor deepEquals here?

@lucasfp13 I don't have metrics, but deepEquals is less error-prone than stringify and === for comparison. (I have some problems with this while comparing objects)

@eduardoformiga
eduardoformiga force-pushed the feat/SFS-1883-load-productGallery-ssr branch from cf61cc9 to 61264f5 Compare March 24, 2025 19:11
@eduardoformiga
eduardoformiga force-pushed the feat/SFS-1883-load-productGallery-ssr branch from 61264f5 to 75bcd62 Compare March 24, 2025 19:22
sort = 'score_desc',
term = '',
selectedFacets = [],
sponsoredCount = 3,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: why is the default 3?

@eduardoformiga eduardoformiga Mar 25, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the default value for sponsored products. I remember that I asked somewhere to the team about this value, and they answered that this is the default value.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, I think I was the one who said that! 🙈 The team actually said that 3 was the default value.

doNotRun: !shouldFetch,
})

const shouldUpdatePages = !hasSameVariables && data !== null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: why is !hasSameVariables not necessary anymore?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's more secure to update the cache every time we fetch it from the Client side to keep the most updated value, especially for the first page (page 0). Imagine that the last fetch from the build time occurred 1 day ago, and we now fetch the data with the same variables on the Client Side. In this scenario, although the variables are the same (cache key), the result could change from the IS/Catalog.

Hypothetical scenario: I don't think the cache mechanism would keep the values for much time (the garbage collector will clean them previously).

@@ -0,0 +1,60 @@
import { useRef } from 'react'

const FIVE_MINUTES = 5 * 60 * 1000

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: sorry, I might have missed it, but why 5 minutes? 👀

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some good reasons:

  1. Balance between update and performance
  2. Latency reduction
  3. Best practice for quasi-dynamic data
  4. Minimizes impact of temporary failures
  5. Control over revalidation

@hellofanny

Copy link
Copy Markdown
Contributor

PLP not refetching to include fuzzy and operator params 🥳
image

Search page
image

@eduardoformiga
eduardoformiga merged commit 9a74405 into main Mar 31, 2025
@eduardoformiga
eduardoformiga deleted the feat/SFS-1883-load-productGallery-ssr branch March 31, 2025 15:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants