Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs - importing next/document outside of pages/_document error

I am getting this error during build time because of Next.js custom document.

So, during the build time I am getting an error saying, Also I have the _document.js in pages/_document.js.

next/document should not be imported outside of pages/_document.js. See https://nextjs.org/docs/messages/no-document-import-in-page.

enter image description here

Please help me!

EDIT

Update next and eslint-config-next to version 11.1.3-canary.7

like image 795
Arya Anish Avatar asked Sep 05 '21 07:09

Arya Anish


People also ask

Why can’t I use nextnext/document?

next/document was imported in a page outside of pages/_document.js (or pages/_document.tsx if you are using TypeScript). This can cause unexpected issues in your application. Only import and use next/document within pages/_document.js (or pages/_document.tsx) to override the default Document component:

Where was nextnext/document imported from?

next/document was imported in a page outside of pages/_document.js (or pages/_document.tsx if you are using TypeScript). This can cause unexpected issues in your application.

How to check if a component has mounted or updated in nextjs?

Since nextjs uses reactjs we can use the useEffect hook which checks if component has mounted or updated. Here is an example. Note that I passed [] as a second argument, this is because useEffect watches what has changed which in this case I just want to check if the document has completed loading.

Why is next JS throwing this error while learning?

I came across this error while learning next js and I couldn't understand what I did wrong. The error is thrown because document is only available inside the browser and not on the server. Next js executes this code on the server side and that's why the error is thrown.


2 Answers

A known issue that is fixed in #28596

If you don't want to update to the canary versions and still keep working normally just exclude it from your .eslintrc.json rules:

"rules": {
    "@next/next/no-document-import-in-page": "off"
}

More info on how to exclude rules here: disabling-rules

like image 107
Nikola Avatar answered Sep 20 '22 18:09

Nikola


This is a known issue from the latest Nextjs update

Quote from Nextjs team:

This is fixed in #28745 and works in 11.1.3-canary.7. Please upgrade to that version if you're experiencing this issue and if you're still seeing the same error, make sure to clear your cache (next lint --no-cache).


Conclude:

You need to update Nextjs and eslint-config-next to 11.1.3-canary.7 and don't forget to clear cache next lint --no-cache

like image 36
Ryan Le Avatar answered Sep 20 '22 18:09

Ryan Le