webfontloader: The WebFontLoader breaks when imported in a server side rendered app
I have a React app running with SSR.
When I import WebFontLoader from 'webfontloader'
the SSR crashes with window is not defined
.
Would it make sense to add a check for typeof window !== 'undefined'
in the package?
If not I would have to fork and maintain such change. Thanks
About this issue
- Original URL
- State: open
- Created 7 years ago
- Reactions: 38
- Comments: 18
In Next js. This is worked well
Yep totally relevant; I was looking to load web fonts in a Frontity project and ran into this error today. My solution was a modified version of @neaumusic with hooks in case someone wants to just copy and paste it:
Although it would be great if this could be handled in the package itself since a big use-case would be SSR apps.
Please add
window
check! Impossible to use forevents
listening without ugly hacking.Here is my approach
I’m dynamically importing the
webfontloader
after checking if it’s in the browser:Issue opened for 2y+ without official feedback, the solution is simple though.
@bramstein Pinging you for official feedback on this 😃
Workarounds exist, but it slows down adoption of this package for universal apps, such as when using https://github.com/zeit/next.js
Personal solution:
For instance, I’ve used it in my
src/components/Head.tsx
:Then, I import
Head
from both my_document.tsx
and otherpages/*.tsx
files._document.tsx
it’s purely import that’s broken, just require inline
@TrejoCode Updated previous answer to provide more information 😃
one option if you are using webpack for transpiling your server side, you can add a
null-loader
as an alias forwebfontloader