Skip to content

[labs/ssr] Investigate interactions with minified or unminified lit-html #4527

Open

Description

@AndrewJakubowicz

Which package(s) are affected?

SSR (@lit-labs/ssr)

Description

Issue was raised by Justin here: #4515 (comment)

Because ssr depends on its own lit-html, there is the possibility that the version of lit-html that ssr imports is minified, while the templates/directives being SSR'd are not minified, or vice-versa. E.g. if a library being SSR'd has its own bundled Lit.

Reproduction

No repro, the objective of this issue is to potentially write a repro PR, or add testing.

Activity

  1. keisha-rw commented on Feb 10, 2024

    @keisha-rw

    Hello @AndrewJakubowicz! I hit this issue when I'm trying to use the app router in a Next 14 app. I have a library where we've enabled SSR, and thus far it's been working well when utilizing the components in a Next app with pages router. But as soon as I start using the app router and try to view the page source, I get this issue:
    image

    I've attached a simplified reproduction of the issue in the form of two repositories. The design-system-ssr repo is our design system library that exports React-wrapped Lit components with SSR enabled. The next-app-router repo is mostly the bare-bones create-next-app code with the app router enabled. I've added a few npm scripts and updated it to use our library, but that's about it. If you look at the README of the design-system-ssr repo, I've given step-by-step instructions on how to reproduce what I'm seeing. It should be as simple as downloading/unzipping the files and running a few commands.

    Is there any work being done on this issue right now? Our organization is going to be enabling the app router for many of our applications soon, and we'd like to continue to have SSR support for those who want to use Next's app router.

    Please let me know if you need any more info or if I can help keep this issue moving. I truly appreciate all the Lit team is doing to enable SSR!

    design-system-ssr.zip
    next-app-router.zip

    cc @augustjk

  2. augustjk commented on Feb 12, 2024

    @augustjk
    Member

    @keisha-rw this issue might be related #3845 (comment)
    I'm not sure why nextjs sometimes fails to use the module with the correct condition but could answer why you're seeing mix of prod and dev versions of lit. For some, forcing it with node options seems to fix it.

    Also the lit nextjs plugin currently won't deeply SSR custom elements with the app router as we're not targeting for those files when injecting our patches. I've been meaning to address this but it'll require some clear documentation on limitations. It's looking like deeply server rendering custom elements producing declarative shadow DOM won't work when used within React Server Components. See #3657

  3. keisha-rw commented on Feb 13, 2024

    @keisha-rw

    Hey @augustjk! Thanks for taking a look! I already had the fix to force dev via node options (I am using it with our pages router implementation), and that didn't seem to do the trick in this instance. I started looking at the different Lit libraries that my next app was pulling in, and I did have @lit-labs/nextjs as a plugin wrapping my next config. I had to force install that using --legacy-peer-deps because this test app that I'm using is on Next 14, so that could definitely be a part of what I was seeing:
    image

    What's interesting is that if I removed the @lit-labs/nextjs plugin, and then installed @lit-labs/ssr-react directly in the next app (since I'm using @lit-labs/ssr-react/enable-lit-ssr.js), then the app router works in that it renders my component (in a client component) and I can see the DSD when I go to view the source of the page. Can you see any potential issues with that approach? I can figure out the dependencies in my library to make sure consumers don't have to import @lit-labs/ssr-react manually, but I'm not sure if it will be a problem to remove the @lit-labs/nextjs plugin.

    FWIW, I'm ok with using client components for a bit (since they still do render on the server) until you guys can get the declarative shadow dom deeply rendering in RSCs. I'd just like my consumers to be able to pick if they want to use the pages or the app router (or both). Fully supporting RSCs can come later for us!

  4. augustjk commented on Feb 13, 2024

    @augustjk
    Member

    Using @lit-labs/ssr-react directly will work for situations where React.createElement() is used to create custom elements. You'd also need to set the jsxImportSource to @lit-labs/ssr-react to handle runtime jsx, but I think that's only for your source code. If you have a dependency in node_modules that is a react component using a custom element inside built with runtime jsx, it won't get SSRed. (This situation is likely very rare)

    I'm going to try and work on plugin support for app router and v14 into the nextjs plugin soon.

  5. keisha-rw commented on Feb 14, 2024

    @keisha-rw

    You are truly a gem, @augustjk! 🌟 Thank you for that. My library sets the jsxImportSource to @lit-labs/ssr-react so I think we're good from that standpoint. I do agree that we're not likely to run into a situation where there's a dependency in node_modules that is a react component using a custom element inside built with runtime jsx, so I'm good with that. I'll reach out again if I run into any further issues, but I really appreciate your timely responses to my questions!

  6. keisha-rw commented on Apr 3, 2024

    @keisha-rw

    Hey @augustjk! 👋 I've been doing more investigation on this lately and it seems to be working at times, but occasionally I still get this error when using the app router, even with a manual install of @lit-labs/ssr-react and having cross-env NODE_OPTIONS=--conditions=development at the beginning of my start script. I delete the .next folder and re-install our library as a dependency in the Next 14 app each time I'm running the app, so I think there's something with how the modules get installed that might be affecting this, but I haven't determined exactly what that may be yet.

    That aside, do you think your monkey-patching updates in this PR #4575 will fix this issue? If so, do you have any idea on when that PR might merge and be released? We'd like to start rolling out SSR with our components in applications that use the app router.

    As always, thanks for your work on this!

  7. augustjk commented on Apr 3, 2024

    @augustjk
    Member

    I don't think #4575 would fix this particular problem as it doesn't change anything about how user code is imported.

    When you say occasionally, is it the same app that sometimes works and sometimes doesn't? Or have you been able to isolate something that consistently causes it like inclusion of particular components? Does the error only happen when you run it in dev mode? If forcing condition doesn't fix, another source of the discrepancy I can think of is there may be pre-bundled code that includes production version of Lit.

    I think ideally we'd want to just be able to avoid this whole thing by making things work across both dev and prod builds, but I don't know if that's really feasible without a hard-code of internal minified method names which seems bad for maintainability.

  8. keisha-rw commented on Apr 4, 2024

    @keisha-rw

    Sorry, I should have clarified that! When I say "occasionally," I mean that it doesn't show when I start the NSK app sometimes, but if I delete the node_modules folder and package-lock.json file and install my dependencies again and restart my Next app (locally), then it will appear. The page and components I'm loading are the same, and I'm not changing how my component library is built. My lib externalizes all lit*|@lit* dependencies in our vite config (build/rollupOptions), by doing this:

    rollupOptions: {
          // Externalize deps that shouldn't be bundled
          external: (id: string) => {
            if (id.match(/^@?lit.*$|^react$/g)) {
              return true;
            }
    
            return false;
          },
          output: {
            entryFileNames: '[format]/[name].js',
            chunkFileNames: '[format]/[name].[hash].js',
          },
        },
    

    (we have multiple vite.config files, but I verified that we're doing this in all our packages)

    And I can see in the es build of my library that the lit dependencies are externalized:
    image

    cjs also looks good to me:
    image

    I'm continuing to investigate and I'll update you as I find more, but thus far I can't see a consistent cause for this.

  9. keisha-rw commented on Apr 4, 2024

    @keisha-rw

    So now it seems I'm getting this message rather consistently. I'll keep poking around to try to get a better idea of when/why this is popping up again, but I still can't quite get a handle on what's causing it to show up.

    Given that the message is coming from ../../node_modules/lit-html/node/development/private-ssr-support.js, I'm assuming the --conditions=development flag is working properly and that there is a production version of lit hanging on somewhere, but I've yet to find it. I threw a bunch of console logs in all the lit dependencies of our library (both the prod and dev versions) to see if maybe one of those was getting included in the build, but I don't see those logs appearing in my Nextjs app when I pull in our built library so it seems like that our library is at least not bundling the lit dependencies with it.

    I also noticed that I'm getting Multiple versions of Lit loaded. Loading multiple versions is not recommended. See https://lit.dev/msg/multiple-versions for more information. in my node console output, but npm ls is showing all lit dependencies at the same version (with dedupes looking normal). I am not, however, seeing this warning in the browser console. And there if I log window.litElementVersions I get ['4.0.4'], window.reactiveElementVersions gives ['2.0.4'], and window.litHtmlVersions gives ['3.1.2']. This could be totally unrelated and I may be chasing my tail here, but I'm assuming that if a prod and dev version of lit were being used I would see this message as well.

    Please let me know if you have any ideas for what I can try to debug to get to the bottom of this!

  10. augustjk commented on Apr 4, 2024

    @augustjk
    Member

    Thanks for the additional info! The deletion of node_modules and package-lock.json was making me think it might be multiple copies of Lit within node_modules, but if npm ls shows everything properly deduped perhaps that's not the root cause.

    Multiple versions of Lit loaded might only be happening server-side due to how Next builds and loads code per route, or however it does partial builds for hot module reloading. Perhaps it's something there that's tripping the error. Just looking at the code though, I don't think multiple copies should be tripping it. I wish there could be a minimal repro I could play with but unfortunately I'm not able to spend too much time on this. :(

    To be clear, this does not happen if you do a production build?

  11. keisha-rw commented on Apr 5, 2024

    @keisha-rw

    I think you're onto something with the idea of looking into how Next builds and loads code per route, because when I use the same code for our lib in a Next 13 app with pages router, I don't see this error at all. The rest of my team has been testing our SSR implementation of our components library in the Next 13/pages router as well and no one has hit this issue there. So I'm pretty confident it's not that we actually have a bundled production version of Lit within our code or I'd think we'd be seeing this issue in our pages router app too.

    I did create a minimal repro in #4527 (comment) if that helps!

    I haven't put this through its paces beyond local development yet, but I can see what happens when I run a production build. I'll try to fake that out locally because we don't have a proper workflow set up with the Next 14/app router app at the moment.

    I'll keep you posted as I continue working on this, but in the meantime, I appreciate any insights you may have! Thanks a ton.

  12. keisha-rw commented on Apr 9, 2024

    @keisha-rw

    I got back to this today and tried to run a production build, but given that this is Next 14, I hit the issue mentioned here: #3657 (comment) and it won't build. So unfortunately I'll need the fix for Next 14 to merge before I can test this out with a production build.

  13. augustjk commented on Apr 25, 2024

    @augustjk
    Member

    @keisha-rw sorry for the delay. The Next 14 support and fix to those errors have now been released. I don't think it would do anything for the dev/prod mixup, but you should be able to test it.

  14. keisha-rw commented on Apr 30, 2024

    @keisha-rw

    @augustjk Thank you!! 🎉 I'll take a look at this hopefully in the next week or two and see how it's working for us. In the meantime, I created a client-side only bundle of our library for Next 14/app router users, so I'm excited to see if we can enable SSR functionality for them! I'll keep you posted.

  15. 12 remaining items

  16. keisha-rw commented on Aug 14, 2024

    @keisha-rw

    Finally got around to trying the nextjs plugin in Nextjs14 /app router, and I'm also running into the same issue. I'm in a monorepo and importing cross-monorepo dependencies which seems to be at least part of the problem? Do we think that its related to different versions of lit-html? or is it different instances of lit-html regardless of version? Would overriding the monorepo version to the same lit-html version everywhere be something to try?

    fwiw, my monorepo (pnpm) seems to only have lit and lit-html 3.1.4. which would satisfy version reqs. Seems like adding a version override wouldnt help much if that is indeed related to the issue.

    Fwiw, I'm also running a monorepo with cross-monorepo dependencies, but we externalize all lit libraries in our build, so I don't think that is what's causing this. It does seem like it has something to do with how the directives are getting patched, because I can't fix it by forcing Next to use only prod Lit dependencies when running locally.

  17. keisha-rw commented on Sep 24, 2024

    @keisha-rw

    Hey @augustjk! 👋

    Any updates on this issue? Can I help by providing a reproduction in some way?

  18. keisha-rw commented on Oct 18, 2024

    @keisha-rw

    Hey @augustjk @AndrewJakubowicz -

    I recently tested out the latest versions of @lit-labs/ssr-react (v0.3.0) and @lit/react (v1.0.6), and we're no longer seeing this issue! We did see a problem where the issue would still appear during Next's fast refresh/hmr, but that ended up being an issue in our library with how we were overriding Lit's default customElement decorator with some of our own logic. I cleaned that up, so things are looking good for us now with Next 14 and the app router!

    Thanks for all the back and forth on this issue. I truly appreciate everyone's time! Keep on being awesome. ❤

  19. augustjk commented on Oct 29, 2024

    @augustjk
    Member

    Thanks so much for the update @keisha-rw and sorry I haven't been able to help much further. I'm glad the issue's been resolved. Do you think an update to nextjs might be responsible? I now see it written that nextjs has been bundling server code when using app router by default, and they have a config option to opt out certain packages described here for v15: https://nextjs.org/blog/next-15#optimizing-bundling-of-external-packages-stable something to look into if the issue ever creeps back up.

  20. JesseKoldewijn commented on Dec 6, 2024

    @JesseKoldewijn

    Hey everybody, The issue described above seems to still happen or has creeped back up again unfortunatly. Running the following Setup:

    Operating System:
      Platform: linux
      Arch: x64
      Version: #1 SMP Tue Nov 5 00:21:55 UTC 2024
      Available memory (MB): 47748
      Available CPU cores: 32
    Binaries:
      Node: 20.12.2
      npm: 10.5.2
      Yarn: 4.1.1
      pnpm: 8.15.9
    Relevant Packages:
      next: 15.0.4-canary.45 // Latest available version is detected (15.0.4-canary.45).
      eslint-config-next: 15.0.4
      react: 19.0.0-rc-7283a213-20241206
      react-dom: 19.0.0-rc-7283a213-20241206
      typescript: 5.7.2
    

    Odly enough, I've tried the external packages config but first render seems to go fine just fine. However on HMR or page reload the error message that links to this issue shows up again. :(

  21. keisha-rw commented on Dec 6, 2024

    @keisha-rw

    Thanks so much for the update @keisha-rw and sorry I haven't been able to help much further. I'm glad the issue's been resolved. Do you think an update to nextjs might be responsible? I now see it written that nextjs has been bundling server code when using app router by default, and they have a config option to opt out certain packages described here for v15: https://nextjs.org/blog/next-15#optimizing-bundling-of-external-packages-stable something to look into if the issue ever creeps back up.

    Interesting! That certainly could have played a part, but we aren't utilizing that serverExternalPackages, so it may not be the issue in our case. I'm thinking the crux of our issue was that our tree-shaking wasn't working properly, so fixing that, plus the updates made on your end with @lit-labs/ssr-react and @lit/react is what eventually got us going. But I'll keep this option in mind if I hit issues in the future!

  22. changed the title [-][ssr] Investigate interactions with minified or unminified lit-html[/-] [+][labs/ssr] Investigate interactions with minified or unminified lit-html[/+] on Jan 20, 2025
  23. moved this to 📋 Triaged in Lit Project Boardon Jan 20, 2025
  24. ChellappanRajan commented on Apr 8, 2025

    @ChellappanRajan

    Hi @augustjk ,

    It's working fine with the app router, but I'm encountering the same issue when switching to the page router. I've tried setting the NODE_OPTIONS=--conditions=development, but it's still not working.

    Is there any update or further advice on how to resolve this?

  25. augustjk commented on Apr 8, 2025

    @augustjk
    Member

    @ChellappanRajan have you tried adding all lit related libraries to serverExternalPackages? besides that i have no idea what else can be done. the issue is likely related to nextjs pre-bundling things possibly without using the correct export conditions so opting out of that is the only thing i can think of.

  26. ADNolan commented on May 7, 2025

    @ADNolan
    Contributor

    I am battling this same issue. Adding the @lit-labs/ssr-react to serverExternalPackage in Next 15 seems to cause custom elements to be shallow rendered instead of deep. Webpack bundle seems to not include ssr-react ssr-client and ssr/lib. Analyzing the webpack bundles that are generated, specifically for Node runtime, this is what Next creates. At this time, nothing stands out as being the problem as to where prod/dev are being mixed. The only package I can see that does not have export conditions for development and default separated out is the lit package. Not sure if that matters since i went into the package.json and manually added development exports for what is included in the analysis.

    Image

    Related stack trace:

    It is possible that both dev mode and production mode Lit was mixed together during SSR. Please comment on the issue: https://github.com/lit/lit/issues/4527" data-next-error-digest="2694225943" data-next-error-stack="Error: Internal error: It is possible that both dev mode and production mode Lit was mixed together during SSR. Please comment on the issue: https://github.com/lit/lit/issues/4527
        at patchDirectiveResolve (webpack-internal:///(ssr)/./node_modules/lit-html/node/development/private-ssr-support.js:53:19)
        at patchIfDirective (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/render-value.js:45:9)
        at patchAnyDirectives (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/render-value.js:60:9)
        at renderTemplateResult (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/render-value.js:566:17)
        at renderTemplateResult.next (<anonymous>)
        at renderValue (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/render-value.js:488:16)
        at renderValue.next (<anonymous>)
        at LitElementRenderer.renderShadow (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/lit-element-renderer.js:108:77)
        at renderShadow.next (<anonymous>)
        at collectResultSync (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr/lib/render-result.js:29:16)
        at Object.litPatchedCreateElement [as createElement] (webpack-internal:///(ssr)/./node_modules/@lit-labs/ssr-react/lib/node/wrap-create-element.js:31:118)
    

    More details from the globalThis in the root layout of a Next 15 app. For the LitHTML and LitElement versions loaded, it seems to be appended to each time a page is loaded.

    litServerRoot: HTMLElement {
        __eventListeners: Map(0) {},
        __captureEventListeners: Map(0) {},
        __shadowRootMode: null,
        __shadowRoot: null,
        __internals: null
      },
      customElements: CustomElementRegistry {
        __definitions: Map(11) {}
      },
      litIssuedWarnings: Set(2) {
        'Lit is in dev mode. Not recommended for production! See https://lit.dev/msg/dev-mode for more information.',
        'Multiple versions of Lit loaded. Loading multiple versions is not recommended. See https://lit.dev/msg/multiple-versions for more information.'
      },
      litPropertyMetadata: WeakMap { <items unknown> },
      reactiveElementVersions: [ '2.1.0', '2.1.0', '2.1.0', '2.1.0', '2.1.0', '2.1.0' ],
      litHtmlVersions: [ '3.3.0', '3.3.0', '3.3.0', '3.3.0', '3.3.0', '3.3.0' ],
      litElementVersions: [ '4.2.0', '4.2.0', '4.2.0', '4.2.0', '4.2.0', '4.2.0' ],
      litSsrReactEnabled: true,
      HTMLElement: [class HTMLElement extends Element],
      Element: [class Element extends EventTarget],

    Deeper into the patching of the React.create element, in dev mode, the first render of a page show the patch is being applied. Confirmed that the Nextjs Lit webpack is the first rule. Subsequent page renders produces the dev/production mixing error.

    Patched Dev JSX Create Element *-image undefined false {
      fileName: '/*/*/*/*/next-app/src/components/latest/client/section-background.tsx',
      lineNumber: 29,
      columnNumber: 5
    } undefined
    Patched Dev JSX Create Element *-image undefined false {
      fileName: '/*/*/*/*/next-app/src/components/latest/client/section-background.tsx',
      lineNumber: 29,
      columnNumber: 5
    } undefined
    Patched Dev JSX Create Element *-header undefined true {
      fileName: '/*/*/*/*/next-app/src/components/latest/client/feature.tsx',
      lineNumber: 21,
      columnNumber: 9
    } undefined
    
    Patched Dev JSX Create Element *-feature undefined false {
      fileName: '/*/*/*/*/next-app/src/components/latest/client/feature.tsx',
      lineNumber: 20,
      columnNumber: 7
    } undefined
    

    when it comes to production mode, it appears its patched all the time. However, the are some rendering issues where the shadow dom seems to be set twice when reloading a page.

    Patched JSX Create Element *-image {
      slot: 'background',
      className: 'sectionBackground',
      fill: 'cover',
      placeholder: 'blur',
      sizes: '(min-width: 960px) 50vw, (min-width: 1200px) 66vw, (min-width: 1400px) 75vw, (min-width: 1600px): 100vh, 33vw',
      figure: false,
      src: '*',
      cdn: undefined,
      priority: true,
      alt: ''
    } undefined
    Patched JSX Create Element *-image {
      slot: 'background',
      className: 'sectionBackground',
      fill: 'cover',
      placeholder: 'blur',
      sizes: '(min-width: 960px) 50vw, (min-width: 1200px) 66vw, (min-width: 1400px) 75vw, (min-width: 1600px): 100vh, 33vw',
      figure: false,
      src: '*',
      cdn: undefined,
      priority: false,
      alt: ''
    } undefined
    Patched JSXS Create Element *-header {
      slot: 'header',
      size: 'medium',
      children: [
        {
          '$$typeof': Symbol(react.transitional.element),
          type: 'h1',
          key: null,
          ref: null,
          props: [Object]
        },
        {
          '$$typeof': Symbol(react.transitional.element),
          type: 'p',
          key: null,
          ref: null,
          props: [Object]
        },
        {
          '$$typeof': Symbol(react.transitional.element),
          type: 'h2',
          key: null,
          ref: null,
          props: [Object]
        }
      ]
    } undefined
    Patched JSX Create Element *-feature {
      variant: 'left',
      children: {
        '$$typeof': Symbol(react.transitional.element),
        type: '*-header',
        key: null,
        ref: null,
        props: { slot: 'header', size: 'medium', children: [Array] }
      }
    } undefined
    Patched JSX Create Element *-section {
      children: {
        '$$typeof': Symbol(react.transitional.element),
        type: '*-feature',
        key: null,
        ref: null,
        props: { variant: 'left', children: [Array] }
      }
    }

    Image of shadowdom having duplicated elements leading to incorrect visuals for subsequent page loads after the initial.

    Image

    I created this StackBlitz sample. It shows that co-locating Lit in a Next.js project is fine and dandy. Only thing I noticed in dev mode is the hydration mismatch because of <template ...></template> when HMR is applied on changes. Downloading the same project and importing a component library built with Lit, it starts to blow up. I confirmed there are no Lit packages bundled in the component library module and Lit is a peer dependency for it.

    More tinkering, I copied components from the external component library and put them into the Next.js app, same as the StackBlitz posted above. Those have not problems working.

    I noticed in the page.js that is generated, for the Lit components defined in the app, they have an (rsc) issurer/context applied. The imports are the ordering expected and that work. There is also a declaration for it in (ssr) as well.

    /***/ "(rsc)/./src/app/simple-alert.tsx":
    /*!**********************************!*\
      !*** ./src/app/simple-alert.tsx ***!
      \**********************************/
    /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
    
    "use strict";
    __webpack_require__.r(__webpack_exports__);
    /* harmony export */ __webpack_require__.d(__webpack_exports__, {
    /* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
    /* harmony export */ });
    /* harmony import */ var _lit_labs_ssr_react_enable_lit_ssr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lit-labs/ssr-react/enable-lit-ssr.js */ "(rsc)/./node_modules/@lit-labs/ssr-react/node/enable-lit-ssr.js");
    /* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-server-dom-webpack/server.edge */ "(rsc)/./node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server-edge.js");
    /* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_1__);
    /*** IMPORTS FROM imports-loader ***/
    

    Components imported from an external library only end up in the (ssr) issurer/context. Looking at the vendor-chunks for Lit packages and the external component library, Lit has both (ssr) and (rsc) while the component library only has (ssr).

    The (rsc) context gets added when I import the self defining component from the external library into one of the RSC files like page or layout, however, that does not solve the issue.

    A bit more sleuthing today, i found that our components that use the classMap directive trigger the error, removing that seemingly allows for SSR to work as expected. Assuming he external component library imports some unpatched version of something required and is probably around Next.js webpack optimizations/bundling. Interesting finding is that if classMapp is added to the SimpleGreeter component that is imported into the same page as an external components, all seems to be well.

  27. augustjk commented on May 9, 2025

    @augustjk
    Member

    @ADNolan wow thank you for the detailed report.

    Sad to hear that serverExternalPackage somehow make it opt out of deeply rendering.

    This error that mentions mixed minified/unminified which points to this issue stems from the changes to directive patching for SSR added in #4515 which explains why adding classMap triggers it. Am I correctly understanding that this particular error only happens when running next dev but not with a production build?

    It might be that the logic used there to traverse the prototype and patch the original Directive class for SSR is brittle, especially with how Next.js handles re-rendering per module and how it brings in the dependency. The addition of a new lit-html version on every page load suggests the core library is not getting deduped and gets loaded anew per render.

    I can't think of an elegant way to alleviate this without resorting to other ways of avoiding the memory leak we tried to fix like described in https://github.com/lit/lit/pull/4515/files#r1465657280, maybe do the branding approach only for process.NODE_ENV === 'development'.

    I've also pulled out a separate issue to #4986 regarding the duplicate DSD and hydration error that should be an easier one to make a workaround for.

  28. ADNolan commented on May 12, 2025

    @ADNolan
    Contributor

    Am I correctly understanding that this particular error only happens when running next dev but not with a production build?

    Most issues are only witnessed in next dev mode.

    The only thing that stands our in production mode is a components has an issue with double rendering of parts in it's shadow root. The div class=" wrapper " part is what is returned from the server after ssr. The nearly identical div class="wrapper is-loaded" above seems to be from client side updates. classMap is used in this component. I'm going to assume styleMap is going to cause the same issue. I do not see any warnings of lit in dev mode on the server logs or browser. I might need to dig more into our component here. I will update the stackblitz with a repro components assuming its not anything wrong with our component logic for ssr support.

    Image

    In our Next.js 15 project, I imported a Lit component that part of the Next.js app and uses classMap. Having that part of the root layout is a stopgap in dev mode. However, that leads to hydration error of the multipletemplate tags, the separate issue you created.

    Most things seem to go back to what is in the (rsc) and (ssr) layers that Next.js generates when is comes to server components (rsc) vs. those that are beyond 'use client' (ssr) boundary.

  29. augustjk commented on May 12, 2025

    @augustjk
    Member

    Double rendering into the shadowroot generally happens if the lit-element-hydration-support.js wasn’t loaded before the component upgrades. @lit-labs/ssr-react loads this in the client export of enable-lit-ssr.js. It might not be getting included in the client bundle or getting added too late.

  30. ADNolan commented on May 13, 2025

    @ADNolan
    Contributor

    Still digging into this, from what I can see, there is not any mixing of dev/production lit modules in Next dev mode on the server.

    NODE:DEVELOPMENT: Lit-HTML Directive
    NODE:DEVELOPMENT: Lit-HTML Private SSR Support
    NODE:DEVELOPMENT: Lit-HTML Directive
    NODE:DEVELOPMENT: Lit-HTML Private SSR Support
    NODE:DEVELOPMENT: ClassMap Directive
    NODE:DEVELOPMENT: StyleMap Directive

    There seems to be something with resolveMethodName ??= directiveClass.prototype._$resolve.name; assignment after the first time a directive is patched holder reference to what _$resolve is now using, ssrResolve. Subsequent usage of the same directive in the same render/request.

    First render/request to a page

    PatchDirectiveResolve: [class ClassMapDirective extends Directive] [Function: _$resolve] [Function: ssrResolve]
    Should Patch Directive: true
    Resolve Method Name: _$resolve
    Should iterate over directive proto: true
    Proto has method for:  _$resolve true
    Proto has method for:  [Function: ssrResolve] false
    Setting Proto Method Resolve method name _$resolve [Function: ssrResolve]
    
    // another part that uses classMap in the same render/request
    PatchDirectiveResolve: [class ClassMapDirective extends Directive] [Function: ssrResolve] [Function: ssrResolve]
    Should Patch Directive: false

    Seconds render/request to the same or different page:

    PatchDirectiveResolve: [class ClassMapDirective extends Directive] [Function: ssrResolve] [Function: ssrResolve]
    Should Patch Directive: true
    Resolve Method Name: ssrResolve
    Should iterate over directive proto: true
    Proto has method for:  ssrResolve false
    Proto has method for:  [Function: ssrResolve] false
     ⨯ Error: Internal error: It is possible that both dev mode and production mode Lit was mixed together during SSR. Please comment on the issue: https://github.com/lit/lit/issues/4527

    What is odd, that the 2nd usage in the first page render is just fine. The same gate to see if a patch needs to happen fails and then its comparing if ssrResolve is on the directive prototype instead of the _$resolve, which will never be the case from what i can tell and hence the error.

    Would if (directiveClass.prototype._$resolve !== resolveOverrideFn) {} be better by comparing the method name instead?
    if (directiveClass.prototype._$resolve.name !== resolveOverrideFn.name) {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions