I have a Next.js (14.1.0) project where i want to use jquery to access the props of some elements. Nothing special. If I get to the page via next routing everything works as designed. But if I reload the page, I get:
⨯ node_modules/jquery/dist/jquery.js (27:26) @ document
⨯ TypeError: Cannot read properties of undefined (reading 'document')
at __webpack_require__ (/workspaces/sandbox/.next/server/webpack-runtime.js:33:42)
at eval (./app/MyComponent.tsx:9:64)
at (ssr)/./app/MyComponent.tsx (/workspaces/sandbox/.next/server/app/page.js:173:1)
at __webpack_require__ (/workspaces/sandbox/.next/server/webpack-runtime.js:33:42)
null
I created i Sandbox whery I only added jquery and a dummy component and still get the error. I haven’t found anything about this error. Anyone got a solution for that or knows, what im doing wrong?
https://codesandbox.io/p/devbox/nextjs-jquery
"use client";
import { useEffect } from "react";
import $ from "jquery";
export default function MyComponent() {
useEffect(() => {
const myClass = $(".myClass");
console.log(myClass.prop("offsetHeight"));
}, []);
return (
<div className="myClass">
</div>
);
}
I tried different Versions of jquery (3.7.1 – 3.5.1), but no difference. I tried adding the jquery-3.7.1.min.js to the head but that still changes anything.
2
Answers
I’m not using jQuery with Next.js, but that seems like a SSR issue :
Your component is rendered one time by your server, then is hydrated in the client. That’s why the offsetHeight is correctly loaded client-side in the browser console, but your have an error in your server console, because document is not defined.
jQuery is a client-side JavaScript library and was not designed to work with server-side rendering (SSR) directly. It probably uses internally the
window
ordocument
globals, which are not set in a SSR environment.Maybe some people will have better answers, but my advice is to try to avoid to use jQuery.
There are plenty of resources online to help you to migrate, like here : https://youmightnotneedjquery.com/
In your example, if you really need the offsetHeight (which is most of the time not the correct way to do it, and would be better to use CSS calc functions if you need to calculate something related to height), I would personnally use a hook like useMeasure from react-hook, which you probably better working with SSR.
Or I would just use plain JS
Please check file "MyComponent.tsx", The error message indicates that an error occurred in a JavaScript script in the file "MyComponent.tsx" on line 9. This error was caused by trying to read the properties of an undefined object. This can happen when trying to access the ‘document’ property of an object that has not been defined. This often occurs when trying to access the DOM (Document Object Model) before the page has fully loaded or when trying to access the DOM outside the browser context such as in a Node.js environment.