On occasion, you may need to use a function or library that only works client-side. This usually is because the library in question accesses something that isn’t available during server-side rendering (SSR), like browser DOM methods.
You’ll need to use one of the workarounds outlined below if your project fails to compile with gatsby develop
or gatsby build
with an error like:
Sometimes the simplest approach is to work around the problem. If you can re-implement your component using a plugin which doesn’t break SSR, that’s probably best.
Workaround 2: Add client-side package via CDNIn the component where you need it, load the package via CDN using a <script />
tag.
To embed your script, you can:
react-helmet
.setHeadComponents
in the onRenderBody
API in gatsby-ssr
.You should then follow React’s guidelines for Integrating with DOM Manipulation Plugins, using the methods available in the React Component Lifecycle to interact with the library you’re using.
Workaround 3: Use React.lazy and Suspense on client-side onlyReact.lazy and Suspense are not ready for server-side rendering, but they can be used by checking that the code is executed only on the client. While this solution is inferior to loadable-components
, that works both on server side and client, it still provides an alternative for dealing with client-side only packages, without an added dependency. Remember that the following code could break if executed without the isSSR
guard.
Install loadable-components and use it as a wrapper for a component that wants to use a client-side only package.
And in your component:
Note: There are other potential workarounds than those listed here. If you’ve had success with another method, check out the contributing docs and add yours!
If all else fails, you may also want to check out the documentation on Debugging HTML Builds.
Start building today on
Netlify!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4