Experience Delivery: Improve LWC Performance with SSR Drew Lau, Sr. Director of Product @drewzie He/Him Greg Whitworth, Sr. Director of Product @gregwhitworth He/Him
A presentation at Dreamforce in September 2023 in San Francisco, CA, USA by Greg Whitworth
Experience Delivery: Improve LWC Performance with SSR Drew Lau, Sr. Director of Product @drewzie He/Him Greg Whitworth, Sr. Director of Product @gregwhitworth He/Him
Forward Looking Statement This presentation contains forward-looking statements about, among other things, trend analyses and future events, future financial performance, anticipated growth, industry prospects, environmental, social and governance goals, and the anticipated benefits of acquired companies. The achievement or success of the matters covered by such forward-looking statements involves risks, uncertainties and assumptions. If any such risks or uncertainties materialize or if any of the assumptions prove incorrect, Salesforce’s results could differ materially from the results expressed or implied by these forward-looking statements. The risks and uncertainties referred to above include those factors discussed in Salesforce’s reports filed from time to time with the Securities and Exchange Commission, including, but not limited to: the impact of, and actions we may take in response to, the COVID-19 pandemic, related public health measures and resulting economic downturn and market volatility; our ability to maintain security levels and service performance meeting the expectations of our customers, and the resources and costs required to avoid unanticipated downtime and prevent, detect and remediate performance degradation and security breaches; the expenses associated with our data centers and third-party infrastructure providers; our ability to secure additional data center capacity; our reliance on third-party hardware, software and platform providers; the effect of evolving domestic and foreign government regulations, including those related to the provision of services on the Internet, those related to accessing the Internet, and those addressing data privacy, cross-border data transfers and import and export controls; current and potential litigation involving us or our industry, including litigation involving acquired entities such as Tableau Software, Inc. and Slack Technologies, Inc., and the resolution or settlement thereof; regulatory developments and regulatory investigations involving us or affecting our industry; our ability to successfully introduce new services and product features, including any efforts to expand our services; the success of our strategy of acquiring or making investments in complementary businesses, joint ventures, services, technologies and intellectual property rights; our ability to complete, on a timely basis or at all, announced transactions; our ability to realize the benefits from acquisitions, strategic partnerships, joint ventures and investments, including our July 2021 acquisition of Slack Technologies, Inc., and successfully integrate acquired businesses and technologies; our ability to compete in the markets in which we participate; the success of our business strategy and our plan to build our business, including our strategy to be a leading provider of enterprise cloud computing applications and platforms; our ability to execute our business plans; our ability to continue to grow unearned revenue and remaining performance obligation; the pace of change and innovation in enterprise cloud computing services; the seasonal nature of our sales cycles; our ability to limit customer attrition and costs related to those efforts; the success of our international expansion strategy; the demands on our personnel and infrastructure resulting from significant growth in our customer base and operations, including as a result of acquisitions; our ability to preserve our workplace culture, including as a result of our decisions regarding our current and future office environments or work-from-home policies; our dependency on the development and maintenance of the infrastructure of the Internet; our real estate and office facilities strategy and related costs and uncertainties; fluctuations in, and our ability to predict, our operating results and cash flows; the variability in our results arising from the accounting for term license revenue products; the performance and fair value of our investments in complementary businesses through our strategic investment portfolio; the impact of future gains or losses from our strategic investment portfolio, including gains or losses from overall market conditions that may affect the publicly traded companies within our strategic investment portfolio; our ability to protect our intellectual property rights; our ability to develop our brands; the impact of foreign currency exchange rate and interest rate fluctuations on our results; the valuation of our deferred tax assets and the release of related valuation allowances; the potential availability of additional tax assets in the future; the impact of new accounting pronouncements and tax laws; uncertainties affecting our ability to estimate our tax rate; uncertainties regarding our tax obligations in connection with potential jurisdictional transfers of intellectual property, including the tax rate, the timing of the transfer and the value of such transferred intellectual property; uncertainties regarding the effect of general economic and market conditions; the impact of geopolitical events; uncertainties regarding the impact of expensing stock options and other equity awards; the sufficiency of our capital resources; our ability to comply with our debt covenants and lease obligations; and the impact of climate change, natural disasters and actual or threatened public health emergencies, including the ongoing COVID-19 pandemic.
Thank you
Why Performance (Still) Matters
[Our site] is always a hot topic of discussion because of high average latencies (in the range of 3-5 seconds), whereas rest of [our] services are well below 1 second. We would like to fix it ASAP Development Manager, anonymous customer
60% of sites do not pass Core Web Vitals www.advancedwebranking.com/blog/core-web-vitals-study
57% of businesses expect more than half of their revenue will come from digital within 2 years Salesforce State of Commerce, 2nd edition
Reimagine How You Deliver B2C-like Experiences with the #1 AI Digital Experience Platform 3x conversion for sites < 1s Partner Portals Marketing Landing Pages +1.11% conversion for every 100m decrease Commerce Storefronts 24% Self-Service Portal BYO sites Salesforce Experience Services Data Cloud AI Cloud Hyperforce lower abandonment rates
Our Performance Journey
KEY CAPABILITIES USE CASES Evolution Of Experience Cloud Visualforce 2013+ Aura 2016+ LWR 2021+ Pixel perfect experiences for external use cases (B2B, B2C) Declarative low code enterprise-grade platform with fast time to value (B2B, B2C) Quickly build connected, real-time, personalized C360 experiences at scale Programmatically build pixel perfect sites and experiences Build low-code sites with out of the box Templates & Components (Pilot) Server-side Rendering with Experience Delivery for B2C perf and scale Connect to CRM data and Business Process Flows Connect to CRM data and Business Process Flows
Largest Contentful Paint LWR vs Aura Performance Real world test results show improved performance across the board Page Aura LCP LWR LCP Homepage 4,966 ms 2,502 ms Search 7,270 ms 3715 ms PDP 5,590 ms 2,876 ms PLP 6,698 ms 2,846 ms Render time of the largest image or text block visible Aura FCP LWR FCP 2.0x 3,776 ms 1,870 ms 2.0x 3,972 ms 2,155 ms 1.9x 3,987 ms 1,718 ms Faster 2.4x 3,780 ms 2,054 ms Faster Faster Faster Faster Faster Note: Numbers are averages across 6 tests per page - Tests were run on a Chrome browser with cable connection in Virginia via https://www.webpagetest.org/ FCP = First Contentful Paint / LCP = Largest Contentful Paint Tests were uncached, with guest users and not behind a CDN 2.0x Faster 1.8x Faster 2.3x 1.8x
Client-side Rendering 📱 Rendering is handled in the browser via JavaScript on user device. Server-side Rendering ☁ Rendering is handled on the “server” and HTML outputs are sent to the browser.
Comparing CSR and SSR Client-side rendering 📱 FCP = First Contentful Paint LCP = Largest Contentful Paint TTI = Time to Interactive Server-side rendering ☁ source: www.patterns.dev
CSR and SSR Considerations Performance Network Performance Rendering TTFB = Time to First Byte FCP = First Contentful Paint LCP = Largest Contentful Paint TTI = Time to Interactive Client-side Rendering 📱 Server-side Rendering ☁ 😀 Faster TTFB 🤔 Slower TTFB → CDN caching critical 😢 Slower FCP/LCP/TTI for heavier JS payloads 😀 Faster FCP/LCP/TTI 😢 Slower on network/compute constrained devices 🤔 Susceptible to scale/load impacts from heavy traffic
CSR and SSR Considerations Performance Network Performance Rendering Developer Experience Code Complexity Developer Experience Infrastructure TTFB = Time to First Byte FCP = First Contentful Paint LCP = Largest Contentful Paint TTI = Time to Interactive Client-side Rendering 📱 Server-side Rendering ☁ 😀 Faster TTFB 🤔 Slower TTFB → CDN caching critical 😢 Slower FCP/LCP/TTI for heavier JS payloads 😀 Faster FCP/LCP/TTI 😢 Slower on network/compute constrained devices 🤔 Susceptible to scale/load impacts from heavy traffic 🔎 Client-side observability 🤔 Isomorphic code 😢 Browser compatibility 🐞 SSR debugging 🤔 Snapshots for SEO/crawlers 💰 Maintaining and budgeting for SSR infrastructure
🤔 Dude, where’s my server?
Introducing Experience Delivery Ope n Sprin Pilot g ‘24 Consumer-grade LWR experiences on Hyperforce B2C-grade Performance with Zero Stress Optimize performance and automate scaling to free up teams Autoscaling • Global CDN • Edge Optimizations • LWR SSR • Core Web Vitals Improved SEO Ensure that your content is always up to date with improved load times and static content Query param support • Hydrated content is indexed Perimeter Security & Compliance Tools Built for You Start secure and stay secure Custom Firewall Rules • Custom Rate Limiting • DDOS • Hyperforce • SOC2 • PCI • Data Residency Up to 60% faster page loads (LCP) for sites using Experience Delivery
Experience Delivery unlocks consumer-grade sites C360 B2C-scale Experiences Experience Delivery 60% faster load time (LCP) Serverless Runtime Deliver Publish Builders Components CDN & Perimeter Security ● ● APIs ● Salesforce Platform Hyperforce B2C LWR Sites B2B LWR Sites B2E LWR Sites
Impact of SSR with Experience Delivery Site Baseline With Experience Delivery Simple 1,074 ms 472 ms 1,501 ms 1,343 ms 1,220 ms 520 ms Guest Context Microsite Guest Context Pilot site Guest Context 56% Faster 11% Faster 57% Faster 2.4x Faster
Adding SSR to LWCs
Preparing your components for Experience Delivery How to ensure that your components can be SSR’d Utilize Light DOM or Native Shadow Both Light DOM and Native Shadow, via mixed-mode, will make it so that your LWC’s can be compiled in Experience Delivery Make your components portable DOM APIs are not available on the server. So leverage conditional checks to avoid unnecessary exceptions that result SSR failures. Test (ESLint, Manual Validation, Einstein) Depending on how your site is built you may need to modify how your CSS is written. Additionally, we need to ensure that the components are SSR’ing correctly. Light DOM: http://sfdc.co/light-dom Mixed-mode: http://sfdc.co/mixed-mode
Choose a rendering paradigm Light DOM Same DOM, same styles The LWCs rendered in Light DOM are rendered without a Shadow DOM, taking advantage of reusing styles and expanded elements tree navigation/querying. Third party integration With light DOM, third-party tools can traverse the DOM, enabling standard browser query APIs like querySelector and querySelectorAll, without traversing the shadow root. Accessibility Enables referencing elements IDs cross components using Light DOM as they are not encapsulated. Native Shadow DOM Encapsulated Development Develop within the boundaries you want. Make changes to a subset of components without breaking other parts of your application or customer environments. Improved Custom Styling Easily apply custom themes to your application. Native Shadow components will create bespoke pages with the now available :slotted and ::part apis.
Light DOM myCmp.html <template lwc:render-mode=”light”> <p>Hello World</p> myCmp.js export default class myCmp extends LightningElement { static renderMode = “light”; </template> }
Native Shadow DOM via mixed-mode myCmp.html <template> <p>Hello World</p> myCmp.js export default class myCmp extends LightningElement { static shadowSupportMode = “any”; </template> }
Choose a rendering paradigm
Making your components portable work outside of a browser context (eg: on a server)
The new SSR environment variable export default class App extends LightningElement { connectedCallback() { if (!import.meta.env.SSR) { window.addEventListener(‘error’, (evt) => { console.error(⚠ Uncaught error: ${evt.message}
); }); } } }
Move async methods to rendered callback export default class App extends LightningElement { @api bookId; @wire(getBook, { id: ‘$bookId’}) book; }
Move async methods to rendered callback export default class App extends LightningElement { renderedCallback() { @api bookId; @wire(getBook, { id: ‘$bookId’}) book; } }
LWC ESLint tools for automated guidance no-restricted-browser-globals-during-ssr Browser APIs must not be accessed when SSR is being done. This rule prevents usage of browser APIs like DOMParser, DocumentFragment etc. in connectedCallback (and in methods called from connectedCallback or anywhere when SSR is being done). no-unsupported-ssr-properties Browser APIs must not be accessed when SSR is being done. This rule prevents usage of browser APIs like querySelector, dispatchEvent, on this in connectedCallback (and in methods called from connectedCallback or anywhere when SSR is being done).
Working with data the getPageData method
Using getPageData hook to SSR data myCmp.js export default class Cmp extends LightningElement { @api label; } export async function getPageData() { // Returns Greg static label = fetch(url) return { props: { label } }; }
Using getPageData hook to SSR data myCmp.html <template> <label>{label}</label> </template>
Using getPageData hook to SSR data Output from SSR <label>Greg</label>
Takeaways How to ensure that your components can be Server Side Rendered Utilize Light DOM or Native Shadow Both Light DOM and Native Shadow, via mixed-mode, will make it so that your LWC’s can be compiled in Experience Delivery Make your components portable DOM APIs are not available on the server. So leverage conditional checks to avoid unnecessary exceptions that result SSR failures. Test Depending on how your site is built you may need to modify how your CSS is written. Additionally, we need to ensure that the components are SSR’ing correctly. Light DOM: http://sfdc.co/light-dom Mixed-mode: http://sfdc.co/mixed-mode
Join the Experience Delivery Open Pilot! Pilot Benefits Learn more and apply here ● Improved page load performance ● Improved SEO through data freshness ● Ability to provide early feedback to influence Salesforce roadmap sfdc.co/df23-experience-delivery
Thank you