NextJS 14 (App router) and Datatables error
NextJS 14 (App router) and Datatables error
Hello,
I'm trying to use Datatables together with new NextJS 14 but without success. I'm receiving following error
⨯ Error: jQuery requires a window with a document
at __webpack_require__ (Q:\ApplicationsWeb\WebLearningLuda\datatables\.next\server\webpack-runtime.js:33:43)
at eval (./app/table.tsx:9:72)
at (ssr)/./app/table.tsx (Q:\ApplicationsWeb\WebLearningLuda\datatables\.next\server\app\page.js:151:1)
at __webpack_require__ (Q:\ApplicationsWeb\WebLearningLuda\datatables\.next\server\webpack-runtime.js:33:43)
I'm trying it on latest 1.13.7 version of datatables:
"datatables.net-bs5": "1.13.7",
"datatables.net-buttons-bs5": "^2.4.1",
"datatables.net-datetime": "^1.5.0",
"datatables.net-responsive-bs5": "^2.5.0",
"datatables.net-searchpanes-bs5": "^2.2.0",
"datatables.net-select-bs5": "^1.7.0",
"jquery": "^3.6.0",
"@types/datatables.net": "^1.10.24",
"@types/jquery": "^3.5.16"
I tried it on completely fresh project as same as on project based on this example: https://codesandbox.io/p/sandbox/stoic-colden-w5ts84?file=%2Fpages%2F_document.js%3A20%2C1&selection=%5B%7B%22endColumn%22%3A114%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A27%2C%22startLineNumber%22%3A12%7D%5D
As soo as I import "datatables.net", the webpack returns mentioned error:
"use client"
import "jquery";
import $ from "jquery";
import "datatables.net";
Any advice please? I'm still learning frontend things so maybe I'm missing something.
Thanks
Answers
I created git repo with my testing app:
https://github.com/rickball/datatables-example
That error means Webpack is transpiling your code into CommonJS. i.e.:
Becomes:
The way jQuery works in a CommonJS environment where there is no
window
object is that you need to pass it a window. The code at the top of jQuery does this and has a good explanation comment.So you need to pass jQuery a window variable - e.g.:
Now - I don't know if you have a
window
variable present. It is global on the client-side browser, but it sounds like you might be using some kind of server-side rendering.I don't know much about NextJS I'm afraid, but I'll try to look into this. Unfortunately that will be tomorrow - I'm rushing about trying to catch my tail today
Allan
Thank you for detailed answer.
I tried to remove import "jquery" from my code but I'm still receiving the same error. It's probably because the same import is in datatables code too.
This is my minimal test case now:
I'm using "use client" fragment to tell NextJS to use this file only on the client-side, but probably the issue is in the webpack itself.
I will be very grateful if you will be able to check my demo project tomorrow. Thanks