Search code examples
next.jsserver-side-renderinglottie

ReferenceError with lottie-react on Next.js 13 - SSR Incompatibility?


I'm encountering a bug in my Next.js 13 application after installing lottie-react. When I compile my project, it completes successfully, but I get a ReferenceError stating that document is not defined. Here's the error log:

 ✓ Compiled in 104ms (1559 modules)
 ⨯ ReferenceError: document is not defined
    at createTag (/Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:30:5)
    at /Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:1316:20
    at /Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:1323:6
    at /Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:1540:4
    at /Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:2:83
    at Object.<anonymous> (/Users/thomas/starknetid/app.starknet.id/node_modules/lottie-web/build/player/lottie.js:5:3)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at mod.require (/Users/thomas/starknetid/app.starknet.id/node_modules/next/dist/server/require-hook.js:64:28)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (/Users/thomas/starknetid/app.starknet.id/node_modules/lottie-react/build/index.js:5:14)
    at Module._compile (node:internal/modules/cjs/loader:1376:14) {
  page: '/register/testingdomain.stark'
}

I suspect this issue might be related to server-side rendering (SSR) incompatibility with lottie-react. In a typical client-side environment, document would be defined, but in SSR, document is not available.

Is there a workaround or a best practice for using lottie-react with Next.js in an SSR context? Do I need to check if SSR is enabled for every component that uses lottie?


Solution

  • The error is caused by the way one of the dependencies handles server and browser environments, it's a known bug but they didn't say when it's getting patched at least not in this answer which explains it much better than me: https://github.com/Gamote/lottie-react/issues/101

    Using node version 18 should fix it because it allows for the existing browser/server. Check the GitHub issue for more details.