nextjs provides the getServerSideProps method (previously called getInitialProps method) to request data before rendering the page. However, the nextjs framework will pass the requested data to the front-end via a script tag in order to keep the front-end and back-end in sync.

1
<script id="__NEXT_DATA__" type="application/json"></script>

But sometimes, we don’t want to expose some raw data to the front-end page, such as some blog sites, news sites, etc., which basically focus on displaying data without the need of isomorphism. So, how to hide the data in __NEXT_DATA__ and show only the constructed html?

1. Usage

There is a pull request on nextjs’ GitHub: Allow disabling runtime JS in production for certain pages (experimental) #11949 that discusses this feature.

Starting with the nextjs@9.4.0 release, an unstable_runtimeJS configuration is provided for components in the pages directory, which, when set to false, will no longer display data from __next_data__.

Note that this setting only takes effect when process.env.NODE_ENV==='production'.

However, it also has a significant side effect in that it causes the entire front-end functionality implemented on the page (such as click events, etc.) to fail, including the child components referenced by the component.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// pages/home.tsx

const Home = ({ nick, age }) => {
  const handleClick = () => {
    console.log('home click');
  };

  return (
    <div>
      <h1 onClick={handleClick}>home</h1>
      <p>{nick}</p>
      <p>{age}</p>
    </div>
  );
};

// 移除__next_data__,移除所有前端的js
export const config = {
  unstable_runtimeJS: false,
};

// https://www.nextjs.cn/docs/basic-features/pages#%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E6%B8%B2%E6%9F%93
export const getServerSideProps = async (context: any) => {
  const { nick, age } = await fetch('api');

  return { props: { nick, age } };
};

The final rendered html structure.

nextjs

2. Side effects

As you can see from the above image, unstable_runtimeJS has very few side effects. It no longer displays the data returned in the getServerSideProps method, but all script tags on the entire page are gone. This results in the component and all its children having no front-end functionality.

3. Summary

Therefore, please do not use this configuration if the page contains front-end mounted events, etc.