Using web components in Next.js Server components

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, 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 adapating my project by defining a CustomElements client component containing the above defineCustomElements, then importing that into a page.tsx server comnponent, 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?

1 Like

Could you solve your problems? I’m trying to migrate to server components and I get the same error messages.

I think I’ve got a pretty good PoC up and running with the latest Next.js & Ionic versions (also using the app router and Next’s components for a hybrid client/server routing solution). Would be keen to hear any feedback on it :slight_smile: