Movatterモバイル変換


[0]ホーム

URL:


Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud.Learn more

SupportLog In

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), likebrowser DOM methods.

You’ll need to use one of the workarounds outlined below if your project fails to compile withgatsby develop orgatsby build with an error like:

Workaround 1: Use a different library or approach

Sometimes the simplest approach is to work around the problem. If you can re-implement your component using a plugin whichdoesn’t break SSR, that’s probably best.

Workaround 2: Add client-side package via CDN

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 usingreact-helmet.
  • Add the script tag directly by using Gatsby’ssetHeadComponents in theonRenderBody API ingatsby-ssr.

You should then follow React’s guidelines forIntegrating with DOM Manipulation Plugins, using the methods available in theReact Component Lifecycle to interact with the library you’re using.

Workaround 3: Use React.lazy and Suspense on client-side only

React.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 toloadable-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 theisSSR guard.

Workaround 4: Load client-side dependent components with loadable-components

Installloadable-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 thecontributing docs and add yours!

If all else fails, you may also want to check out the documentation onDebugging HTML Builds.

Start building today on Netlify!

Gatsby is powered by the amazing Gatsby
community and Gatsby, the company.


[8]ページ先頭

©2009-2025 Movatter.jp