0

Background

Hi!

I develop a components library and I have to build it to import in another project. So, I configurated webpack and tried to import a random component and got SSR error:

Server Error ReferenceError: document is not defined

Call Stack

insertStyleElement

node_modules/lib/dist/index.js (367:14)

Of course code (after build) below raises error in nextjs app. Its internal style-loader function.

function insertStyleElement(options) {
  var style = document.createElement('style');
  ...
}

Configs

All configs are here

Stacks

Lib stack:

  • React
  • TypeScript
  • css-modules + postcss

Main App stack:

  • TypeScript
  • Nextjs

Question

I suppose that trouble comes from style-loader (insertStyleElement is exporting from there). Where did I make mistake?

1 Answer 1

0

Problem is not about webpack loaders. You try to call document.createElement but there is no document/window space on the server (you are able to work with it only in the browser).

You need to add helper inside your library:

export const isClient = () => typeof window !== 'undefined';

And then you can use it like:

var style = isClient() && document.createElement('style');
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. I know about isClient helper but I dont use the document object in code. insertStyleElement is the loader internal function so I cant use something like isClient helper.
Oh, sorry. stackoverflow.com/questions/53951861/… Suppose it can help.
Thx. I fixed my issues with extracting css with MiniCssExtractPlugin. i will try another methods but MiniCssExtractPlugin did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.