Configure Components for Server-Side Rendering (SSR)

To successfully render a component on the server side, it has to meet all of the following criteria:

  1. The functions that execute during SSR must be portable
  2. The functions that execute during SSR must be synchronous.
  3. The component uses light DOM (recommended) or native shadow DOM.

The LWC framework executes these functions for each component and its imported dependencies during SSR:

  • constructor
  • connectedCallback
  • getters
  • setters
  • any other functions called by these functions

The fastest way to get your components ready for SSR is to use a combination of these tools:

A component is portable if it can run without browser APIs. If your component uses browser APIs, you MUST modify those components to ensure it doesn't assume that those APIs are always available.

Your components can’t have any dependencies on browser APIs because the server isn’t a browser. If a component has non-portable code, it will break your site.

Here are a few examples of non-portable code and objects that your components should not use:

  • window
  • document
  • selector functions (querySelector, querySelectorAll, ...)
  • JavaScript eventing

Since the SSR process for Lightning web components (LWCs) runs in one synchronous pass, we recommend having only synchronous code in server-rendered pages and components.

Server-rendered pages and components can include asynchronous code that doesn't execute on the server. For example, you can include asynchronous code in renderedCallBack() or event handlers, but you can't add it to connectedCallback() or getters. To test if asynchronous code is unsafe, use the ESLint plugin.

Otherwise, server-side asynchronous code executes but doesn't complete during SSR. The resulting page won't break, but it can render unexpected content (that's often difficult to debug).

Asynchronous code includes:

By default, server-rendered components are rendered in native shadow DOM. However, we recommend using light DOM instead.

Light DOM eases third-party integrations (like Google Analytics) and global styling. Enabling light DOM ensures that LWC renders regular HTML markup instead of creating a native web component. The markup is also referred to as light DOM since it isn’t contained within a shadow root.

To enable light DOM on your Lightning web component, use the renderMode static property.

In your template, use the lwc:render-mode directive.

Shadow DOM encapsulates a component's internals and styling. Server-rendered components can use native shadow DOM instead of light DOM.

Synthetic shadow DOM is not supported due to limitations on browser API usage.

After you've configured a component for SSR, make sure it follows the Best Practices for Portable Components.

See Also