Skip to content

SSR with Vite – Styles Are Not Included in Server-Rendered HTML #7289

@MLaszczewski

Description

@MLaszczewski

Issue Description

When using PrimeVue 4 with Vite SSR, styles are not included in the server-rendered HTML. Since PrimeVue components inject their styles when mounted, this works fine for CSR. However, in SSR, the styles are missing until hydration occurs, causing a flash of unstyled content (FOUC).

Unlike Nuxt (which has a module for handling this), there’s no documented solution for Vite SSR.

Expected Behavior

PrimeVue should provide an official method for injecting styles into the server-rendered output so that the page is fully styled upon initial load.

Current Workaround

To avoid FOUC, I manually extract and inject styles after renderToString, like this:

/// Imports
import { Theme } from '@primeuix/styled'
import { Base, BaseStyle } from '@primevue/core'

/// Before renderToString
let usedStyles = new Set()
Base.setLoadedStyleName = async (name) => usedStyles.add(name)

/// After renderToString
const styleSheets = []
styleSheets.push(`<style type="text/css" data-primevue-style-id="layer-order">${
  BaseStyle.getLayerOrderThemeCSS()}</style>`)
BaseStyle.getLayerOrderThemeCSS()

styleSheets.push(Theme.getCommonStyleSheet())
for(const name of usedStyles) {
  styleSheets.push(Theme.getStyleSheet(name))
  const styleModule = await import(`primevue/${name}/style`)
  styleSheets.push(styleModule.default.getThemeStyleSheet())
}
styleSheets.push(BaseStyle.getThemeStyleSheet())

renderedHead.headTags += styleSheets.join('\n')

Would love to hear if there’s an official approach to handling this! 🚀

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: Pending ReviewIssue or pull request is being reviewed by Core Team

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions