Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove __NEXT_DATA__ from dom in NextJs?

Because of __NEXT_DATA__ element DOM size is getting very high and it is affecting to the performance. Can anyone plz help me to remove __NEXT_DATA__ from DOM? I am using full server-side rendering with dynamic routes in Next.js.

like image 517
Archana Agivale Avatar asked Jan 02 '26 07:01

Archana Agivale


2 Answers

TLDR: If you would(/could) remove the __NEXT_DATA__ script tag, React wouldn't be able to hydrate. You either hardcode the data in the page or try to reduce your pageProps payload, returned from getServerSideProps.

I came upon this issue also recently, where I asked myself, why would there be a need for the content to be included in the HTML 2 times.

  1. As the content itself - when your NextJS renders the appropriate HTML and sends it to the client
  2. As JSON in <script> tag - This is because of the need for rehydration on the client side.

"Solutions"

  • Returning only necessary data from data-fetching method - I can recommend reading up on this article Reducing HTML payload with NextJS, in which they talk about formatting / aggregating the necessary data and returning only the needed fields.
  • Not using the data-fetching method and hardcoding static content - The idea behind using static data fetching, if not using revalidate option, is that the content shouldn't be changing (maybe ever). So in that case, why couldn't we hardcode the data in the page itself. Althought downside of this of course is, having to write it all out manually / download the required content to some JSON / object and then use it in the page like so.

Reading

  1. Here's a github link with related discussion in next in which you might be interested.
  2. Blog post about reducing the size of __NEXT_DATA__ - by Liran Cohen.
like image 184
Jan Karnik Avatar answered Jan 06 '26 02:01

Jan Karnik


Sometimes you might not require some of the __NEXT_DATA__ props during client side rendering.

To drop those props, you can mutate the NextScript.getInlineScriptSource function in the _document.tsx file. Here is an example:

// _document.tsx

const nextInlineScriptSource = NextScript.getInlineScriptSource;
NextScript.getInlineScriptSource = (props) => {
  if (props?.__NEXT_DATA__?.foo) {
    props.__NEXT_DATA__.foo = 'bar';
  }
  return nextInlineScriptSource(props);
};
like image 20
Neeraj Rajpurohit Avatar answered Jan 06 '26 03:01

Neeraj Rajpurohit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!