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?
I just found out a workaround, basically, just import lottie-web after component mount, with "npm run dev" the asset is redered twice, this problem disappears in production build
"use client"
import * as data from '../../public/404.json';
import { useEffect, useRef } from "react";
export default function AnimationNotFound() {
let animationRef = useRef(null);
async function getLottie() {
const lot = await import("lottie-web");
lot.default.loadAnimation({
autoplay: true,
loop: true,
animationData:data,
container:animationRef.current
})
}
useEffect(() => {
getLottie();
}, []);
return (
<div ref={animationRef}></div>
);
}