How do I use CSS Houdini in Next.js

571 views Asked by At

I would like to use CSS Houdini in a Next.js project I am building. I have installed, via yarn, both the CSS Houdini package I want to use along with css-paint-polyfill. I am following the webpack instructions here https://houdini.how/usage

Here is my component:

import 'css-paint-polyfill';
import workletURL from 'url-loader!css-houdini-lines';
import styles from './Separator.module.css';

CSS.paintWorklet.addModule(workletURL);

export default function Separator() {
  return <div className={styles.separator} />;
}

I am getting the dreaded

error - ReferenceError: window is not defined
at /home/tithos/code/web/new-tim/node_modules/css-paint-polyfill/dist/css-paint-polyfill.js:1:239

I tried putting the import for css-paint-polyfill in a useEffect, but the throw another error. I even tried const DynamicComponent = dynamic(() => import('../components/hello')) from https://nextjs.org/docs/advanced-features/dynamic-import, but I did not know how to reference the library.

Has any one solved this?

1

There are 1 answers

1
Dániel Emőd Kovács On

Seems like CSS Paint Polyfill eagerly accesses window, which means it will throw an error when in an environment which has no window, such as server phase of Next. There are multiple things you can do.

  1. Modify your next.config.js to stub the aforementioned module when for Webpack when isServer is true. You can follow this page of the Next docs for this.
  2. Create a dynamic component that's only imported on the client (I see you've tried this, but it should have worked, so maybe if you shared what you did in this regard, I could work out what's wrong with your approach).
  3. Create an issue and send in a PR to the repository where the Polyfill is hosted to lazily access window depending on whether it's available or not.