2

Prior the /app router and default server components in Next.js 13, I was able to use web components generated via StencilJS as per the with-stencil starter, by defining the custom elements in _app.tsx.

import { useLayoutEffect } from 'react'
import { applyPolyfills, defineCustomElements } from 'test-component/loader'

export default function App({ Component, pageProps }) {
  useLayoutEffect(() => {
    applyPolyfills().then(() => {
      defineCustomElements(window)
    })
  }, [])
  return <Component {...pageProps} />
}

// Then use in any component like so
export default function Home() {
  return (
    <div>
      <my-component first="Next.js" last="The React Framework"></my-component>
    </div>
  )
}

With the advent of default Server components, is it even possible to use web components (which to my knowledge rely on browser APIs) in server components? I tried adapting my project by defining a CustomElements client component containing the above defineCustomElements, then importing that into a page.tsx server component,

'use client';
import { useLayoutEffect } from "react";
import { applyPolyfills, defineCustomElements } from 'path/to/your/stencil-components/loader';


const CustomElements = () => {
  useLayoutEffect(() => {
    applyPolyfills().then(() => {
      defineCustomElements(window)
    })
  }, [])
  return <></>;
}

export default CustomElements;

but the web components don't render and I get errors like

TypeError: Cannot read properties of undefined (reading '$hostElement$')
TypeError: Cannot read properties of undefined (reading '$instanceValues$')

from the web component library.

Any ideas?

5tormTrooper
  • 893
  • 7
  • 21
  • This `defineCustomElements` remind of https://stackoverflow.com/questions/75951134/next-js-app-folder-is-there-some-entry-point-a-direct-replacement-for-app-t/75963374. Check the answer there. Maybe it would help. – Youssouf Oumar May 09 '23 at 17:50
  • @YoussoufOumar yea as mentioned I tried that approach. That's where I get the errors. I've updated my example with the CustomElements component. – 5tormTrooper May 09 '23 at 18:35
  • I actually am not sure if that's the same question as mine - this actually looks like an error coming from the web component library. Or where actually is the error thrown? – sandrooco May 10 '23 at 11:18
  • Any solution? I'm blocked with the same problem – leroj7 Jun 09 '23 at 07:31

0 Answers0