Web Components in Server-Side Rendered (SSR) and Static-Site Generated (SSG) in Next.js Applications

Compared to other web development frameworks, Next.js has become very popular because of its support for a number of rendering strategies that result in highly performant frontend applications: By having the content readily available in the initial HTML document, less client-side rendering takes place. All the client has to do is hydrate the components and make them functional. The less dynamic content the client renders, the better the application's performance and SEO. Search engine bots like Googlebot can visit the application, immediately crawl (and understand) its content and rank it high on search engines. If you use Web Components to build your application's UI, then you don't need to worry about the breaking changes that third-party JavaScript frameworks/libraries notoriously cause (as a result of rapid development and release cycles). Your application performs equally as well as (or better than) applications that use these frameworks/libraries. Additionally, the low-level, native APIs of Web Components are based on an official W3 specification and let you develop encapsulated, modular and reusable components (represented as custom HTML elements). However, you will come across several limitations that can prevent the application from taking advantage of these rendering strategies: Custom web components are defined with a class that extends from HTMLElement and registered using the customElements.define method. Since browser APIs do not exist in the context of Node.js, Next.js's build tools cannot run code that uses these APIs. This also applies to the Shadow DOM . The Shadow DOM's imperative nature prevents custom web components from being rendered by either the server or build tools. The missing browser APIs can be "polyfilled" and "shimmed" for these environments before the custom web component is defined with the class keyword. This approach makes it possible to simulate the DOM and output an HTML string for the initial HTML document, but it lacks the ability to hydrate components. Fortunately, the Declarative Shadow DOM provides an alternative way for implementing web components that complements server-side rendering and static-site generation. Below, I'm going to show you how to pre-render custom web components in Next.js. By extracting the logic used to create the template that is attached to the component's innerHTML into a separate module, the server (or build tools) never has to run code that uses browser APIs like HTMLElement and customElements . For any custom web component that has a shadow root attached to it, we will use the Declarative Shadow DOM so that the shadow root is attached to it and readily available at the time of the component's instantiation. To get started, scaffold a new Next.js application with the TypeScript boilerplate template. Once the application has been scaffolded, change the current directory to the application's directory, like so: In this tutorial, we want to test that the custom web components are pre-rendered when the application is server-side rendered or static-site generated. Next.js provides several CLI commands for building and running the application: dev , build , start and lint . For server-side rendering, we want to build a production version of the application and spin up a Next.js production server that runs getServerSideProps on each incoming request and pre-renders this application with the returned props. Since next start starts the server, let's add a prestart npm script that runs the build npm script, which builds the application via the next build command. ( package.json ) For static-site generation, we want to export the application to static HTML. Let's add an export npm script that exports the application to static HTML via the next export command. Since the application must be built prior to being exported, let's also add a preexport npm script that runs the build npm script. ( package.json ) Within the pages/index.tsx file, remove the children elements under the <main /> element, and replace the text within the <footer /> element's child <a /> element with the text "Powered by Vercel." ( pages/index.tsx ) Now that there are no more <Image /> components in the application, let's remove the import Image from 'next/image' line from the pages/index.tsx file. This Next.js application will feature two custom web components: Since the <pinned-location-link /> component will not use a Shadow DOM, let's create this component such that its rendering logic (what's set to innerHTML ) is completely decoupled from its class declaration. First, create a directory named components , which will house these custom web components. Within this directory, create two subdirectories, pinned-location-link and info-tooltip , each of which will contain two files: Let's define and register the <pinned-location-link /> component. To keep things simple, components' props will only come from their attributes. ( components/pinned-location-link/component.ts ) Note #1 : When using these components in JSX/TSX code, attributes must be prefixed with data- (custom data attributes). Otherwise, TypeScript will raise the following error: Property '<attribute>' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>' . Note #2 : connectedCallback is a special lifecycle callback that gets called after the custom element is inserted into the DOM. Note #3 : To fix the TypeScript error Type 'NamedNodeMap' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. on [...this.attributes] , set the downlevelIteration option to true under the compilerOptions in the tsconfig.json file. This allows you to iterate over iterators in TypeScript code. Attributes for any node are represented as a NamedNodeMap , not as an Array . The connectedCallback lifecycle callback... Since all JSX elements come with a dangerouslySetInnerHTML property, this approach allows Next.js to not have to run the component.ts file to set the component's innerHTML . You don't have to polyfill and shim browser APIs like HTMLElement and customElements for Next.js's build tools. Let's write the template function that generates the component's stringified HTML from the passed props. ( components/pinned-location-link/template.ts ) This template function supports several types of location search queries used in a Google Maps URL, each of which is optional: Based on the passed props, we can add a class to the <a /> element in the stringified HTML. We can also modify the Google Maps URL and the text displayed within its child <span /> element. Inside of the <main /> element of the <Home /> page component in the pages/index.tsx file, add the <pinned-location-link /> component, like so: ( pages/index.tsx ) Currently, Next.js doesn't know what the HTML content inside of the <pinned-location-link /> component is supposed to be. However, if we give it the dangerouslySetInnerHTML property and set the __html key to the result of the component's template function, then Next.js can render the component's HTML content without ever having to define or register it as a custom element. To demonstrate this, let's import the template function from the components/pinned-location-link/template.ts file and add the dangerouslySetInnerHTML property to the component, like so: ( pages/index.tsx ) Note : If any data comes from a third-party service, then you may want to pass the result of template to an HTML sanitizer like DOMPurify to mitigate cross-site scripting (XSS) attacks. Unfortunately, TypeScript raises the following error: Property 'pinned-location-link' does not exist on type 'JSX.IntrinsicElements' . Since the <pinned-location-link /> component is not a React component or standard HTML element, TypeScript does not recognize it as a valid JSX element. Therefore, we must create a type definition file ( types/index.d.ts ) that lets us add custom elements to the JSX.IntrinsicElements global interface: ( types/index.d.ts ) With the TypeScript error no longer popping up in VSCode, let's build the application and run it in production mode: Note : Add export {}; to the empty components/info-tooltip/component.ts and components/info-tooltip/template.ts files. Otherwise, the build will fail. Within a browser, visit localhost:3000 . Then, disable JavaScript and reload the page. When you inspect the elements on the page, you will see that the HTML content of the <pinned-location-link /> component still exists despite JavaScript being disabled. Now, let's define and register the <info-tooltip /> component. Unlike the <pinned-location-link /> component, this component will use the Shadow DOM. A hidden, separate DOM will be attached to the component (the custom element becomes a shadow host). All CSS rules defined within the Shadow DOM will be scoped to elements that are part of the shadow tree, and CSS rules outside of the Shadow DOM that specify the same selectors will have no effect on these elements. The Shadow DOM will be implemented declaratively, not imperatively. The Declarative Shadow DOM involves wrapping the component's content in a <template /> element with a shadowroot attribute. When this attribute is set to open , the shadow root's internal features can be accessed with JavaScript. On the other hand, imperatively setting up the shadow root involves calling the Element.attachShadow method to attach a shadow tree to the custom element. ( components/info-tooltip/component.ts ) Since both the <pinned-location-link /> and <info-tooltip /> components extract props from data attributes, we should refactor this logic into a function named extractPropsFromAttrs so that it can be shared by both components. ( shared/index.ts ) Don't forget to update the components/pinned-location-link/component.ts file so that the connectedCallback lifecycle callback calls this method. ( components/pinned-location-link/component.ts ) Once you have made that update, create the <info-tooltip /> component's template. The <info-tooltip /> component only accepts two props: ( components/info-tooltip/template.ts ) Unlike the <pinned-location-link /> component's template, the <info-tooltip /> component's template gets wrapped within a <template /> element by default during server-side rendering or static-site generation. If the Declarative Shadow Root does not exist when the page is initially loaded, then via client-side rendering, the shadow root gets set up imperatively with the Element.attachShadow method. The <template /> element is only for the Declarative Shadow DOM. For us to use it in the JSX code, add the <info-tooltip /> custom element to the JSX.IntrinsicElements global interface. ( types/index.d.ts ) With everything completed, let's render this component within the <Home /> page component. Import the template function from the components/info-tooltip/template.ts file and add the dangerouslySetInnerHTML property to the component, like so: Note : Since both files, components/info-tooltip/template.ts and components/pinned-location-link/template.ts , export a template function as the default export, both functions will need to be renamed to avoid conflicting function names. Let's rebuild the application and run it in production mode: Within a browser, revisit localhost:3000 . JavaScript should still be disabled from before. When you inspect the elements on the page, you will see that the HTML content of the <info-tooltip /> component lives within a Shadow DOM despite JavaScript being disabled. Suppose we re-enable JavaScript. If we add data attributes to the <pinned-location-link /> and <info-tooltip /> components rendered in the <Home /> page component, then the components should initially be rendered with the props passed to the template function for the dangerouslySetInnerHTML property. Once client-side rendering takes place, the components should be rendered with the props extracted from the data attributes. Let's add some data attributes to these components. ( pages/index.tsx ) Then, rebuild the application and run it in production mode: When you reload the page, you will see that nothing has changed. This is because we have not yet imported the component.ts files into the Next.js application. Since the server and Next.js build tools do not run the useEffect lifecycle hook, let's dynamically import these files in useEffect . After the initial render of the page, useEffect will run on the client-side, import these files and execute them. These custom elements will officially be registered by the browser, and the component will be updated and re-rendered using the data attributes. ( pages/index.tsx ) Then, let's temporarily modify the components/info-tooltip/component.ts file so that regardless of whether or not the Declarative Shadow Root exists as a result of SSR/SSG, the <info-tooltip /> component's content will be updated using the props extracted from the component's data attributes: ( components/info-tooltip/component.ts ) Rebuild the application once more and run it in production mode: When you reload the page, you will see that the content of the components is initially rendered via the dangerouslySetInnnerHTML property. As soon as the client fetches the component.ts files and executes them, the content of the components updates accordingly with the data attributes set on these components. If you disable JavaScript and reload the page again, then the client never fetches the component.ts files, and you fallback to the components in their initial render state once more. Afterwards, undo the changes made to the components/info-tooltip/component.ts file. Now let's test that the application works properly when static-site generated. Run the following command to export the application as static HTML: With the static HTML (e.g., index.html and 404.html files) exported to an out directory by default, serve the directory as a static site via serve : Within a browser, visit localhost:3000 and reload the page with JavaScript enabled/disabled to verify everything still works properly. Currently, only Google Chrome and Microsoft Edge natively support Declarative Shadow DOM. To provide support for this feature in other browsers, we must use the @webcomponents/template-shadowroot ponyfill . Unlike polyfills, which are found in HTML document's <head /> , ponyfills are found at the end of the HTML document's <body /> . Since it gets executed after the DOM is fully loaded, the ponyfill will be able to find all the <template /> elements that have a shadowroot attribute and convert them into shadow roots on the <template /> elements' parent elements (done via the ponyfill's hydrateShadowRoots method). In the Next.js application, we will dynamically import the ponyfill in the useEffect lifecycle hook after the <Home /> page component's initial render. Once the ponyfill has been successfully imported, we check if the client natively supports Declarative Shadow DOM. If not, then we call hydrateShadowRoots on the HTML document's <body /> . Afterwards, we proceed to dynamically import the two component.ts files like before. First, let's install the @webcomponents/template-shadowroot ponyfill: Then, dynamically import the ponyfill in the useEffect lifecycle hook, like so: ( pages/index.tsx ) If you find yourself stuck at any point while working through this tutorial, then feel free to visit the main branch of this GitHub repository here for the code. Try passing data to custom web components from props returned by getServerSideProps and getStaticProps . If you want to learn more advanced techniques with web components, then check out the Fullstack Web Components  book by Steve Belovarich, a software engineer who has many years of industry experience building out enterprise-grade web applications.

Thumbnail Image of Tutorial Web Components in Server-Side Rendered (SSR) and Static-Site Generated (SSG) in Next.js Applications