乐闻世界logo
搜索文章和话题

How can I use getInitialProps only during the NextJS site build?

1个答案

1

In Next.js, getInitialProps is a method used for asynchronously fetching data. It can run on the server or client side, depending on how the page is loaded and accessed. If you want to use getInitialProps only during the build process, i.e., to fetch data only when generating static pages on the server and not on the client, you can adopt the following strategies:

1. Use getStaticProps instead of getInitialProps

Starting from Next.js 9.3, it is recommended to use getStaticProps instead of getInitialProps because getStaticProps runs exclusively during the build process and never on the client side. This meets your requirements.

Example:

jsx
export async function getStaticProps() { // Assume we fetch data from some API const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data }, // Will be passed to the page component as props }; } function HomePage({ data }) { return ( <div> <h1>Welcome to Our Site!</h1> <p>Data: {JSON.stringify(data)}</p> </div> ); } export default HomePage;

In this example, the data is fetched only during the build process from the API and passed to the page component as props. The client does not re-fetch the data.

2. Clarify the scenario and requirements

Although it is generally not recommended to use getInitialProps solely during the build process, if specific requirements exist, you can add environment detection logic within getInitialProps to fetch data only on the server side.

Example:

jsx
Page.getInitialProps = async (ctx) => { if (!ctx.req) { // Client-side environment, do nothing return {}; } // Server-side environment, fetch data from API const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { data }; };

In this example, getInitialProps ensures the data fetching logic runs only on the server side by checking ctx.req (which exists only during server-side rendering). This way, the client does not re-fetch the data.

Conclusion

It is recommended to use getStaticProps based on project requirements. This not only satisfies the need for fetching data during the build process but also ensures optimal page performance and efficiency. If specific situations require using getInitialProps, appropriate environment detection logic should be added to ensure it runs exclusively on the server side.

2024年7月18日 00:59 回复

你的答案