Search code examples
next.jsserver-side-rendering

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.


Solution

  • 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.