How we passed Core Web Vitals — LCP — Server Side Rendering React
TL:DR — To get our LCP element rendered as early as possible we server-side rendered our React components.
Server side rendering
Google developers defines it as
Server rendering generates the full HTML for a page on the server in response to navigation. This avoids additional round-trips for data fetching and templating on the client, since it’s handled before the browser gets a response.
So instead of running Javascript in the client to create the HTML for the page, you run the Javascript on your server.
Server side and client side rendering in our app
We use Ruby on Rails so server side rendering (SSR) is our default. However for key elements we use React which by default is client-side rendered. These key elements contain our LCP(Largest Contentful Paint) element on our two highest traffic pages our Product Listing Page (PLP) and our Product Detail Page (PDP).
This means that we have a delay in how quickly those elements can appear on the page as we have to first, load and run all the related Javascript to render the elements.
How we did it
We use the react-rails ruby gem which has an option to SSR.
# Client side rendered component
<%= react_component "ListingCarousel", { listing: @listing }) %># Server side rendered component
<%= react_component "ListingCarousel", { listing: @listing }, prerender: true) %>
Complications
So many complications!
- Getting SSR working with webpacker chunks
- Manage code execution for if code is running on the client or the server
- Don’t SSR for bots as it started causing timeouts when we did crawls (coming soon) TODO
- We had to get our image preloading working before we saw any benefits from SSR on our PDP.
Impact
TODO
Show gifs
Add PLP data