Using Client-Side Only Packages
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.
In the component where you need it, load the package via CDN using a
<script /> tag.
To embed your script, you can:
- Include it in a custom component as needed using
- Add the script tag directly in your base HTML using Gatsby’s html.js
Install loadable-components and use it as a wrapper for a component that wants to use a client-side only package.
React.lazy and Suspense are still not ready for server-side rendering, but they can still 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
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.
Edit this page on GitHub