styled-components/polished

cssVar is not working with SSR due to "document is not defined" error

fatihtelis opened this issue · 5 comments

  • polished version: 3.6.4
  • JSS-in_CSS library and version: styled-components 4.4.1
  • Any relevant JS library and version: react 16.3.1 + next 9.4.4

Mixin/Helper/Shorthand Usage

background:  ${lighten(0.2, cssVar('--bg'))};

What You Are Seeing

I'm using polished with Next.js. cssVar is not working properly with SSR (Server Side Rendering).

ReferenceError: document is not defined

Since document is not defined on server side, it gives an error. A basic check for whether document is defined or not may solve the issue.

What You Expected To See

cssVar has to be worked with SSR.

fikip commented

I'm having similar issues, albeit my error message is different.

Here's what I'm using:

  • polished version: 3.6.4
  • JSS-in_CSS library and version: styled-components 5.1.1
  • Any relevant JS library and version: react 16.13.1 + next 9.4.4

I'm using polished in a styled component, like this:

export const NewLoader = styled.div`
  position: absolute;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: ${transparentize(0.3, "var(--white)")};
  z-index: 420;
`

The server-side error I receive is: error - PolishedError: Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.

I've tried using the cssVar function instead of inlining the variable, the error is identical to the OP's in that case.

@bozskejkaja The scenario where you are using just the string value is expected. cssVar is the only way to fetch CSS Variables at runtime.

We are looking into the SSR issue when it can't find the document object.

We are looking into the SSR issue when it can't find the document object.

if (typeof document !== 'undefined' && document.documentElement !== null) {
    variableValue = getComputedStyle(document.documentElement).getPropertyValue(
      cssVariable,
    )
}

may solve the issue from the file "cssVar.js", line 41;
https://github.com/styled-components/polished/blob/master/src/helpers/cssVar.js

@fatihtelis v3.6.5 will properly handle this exception with error messaging. 4.0 will bring it inline with native CSS functionality to pass a proper fallback value. We will also look into better SSR support as part of that, but more research is needed there. Let us know if the proper exception handling takes care of your initial issue.

Hello, does anyone know how to get this to work with remix and Chakra, if I pass the default value to cssVar() on the latest version (v4.2.2), on page load there is a brief flash of the default colour, please let me know if you require any further details