Is there any global place in Next.js to fetch menu-items(server-side) that I can pass to my Layout component.
Since, I can't do that in index.js
as if somebody directly opens different route for eg: /about
then the data will not be fetch.
I tried doing that in _app
by implementing it's static getInitialProps
method but I'm not sure if it's a good practice and also it will disable Automatic Static Optimization in pages without Static Generation.
Any suggestion?
In Next js, data fetching is a strategy. Next.js uses getStaticProps or getServerSideProps to enhance different fetching capabilities. Even though both are used to pre-render data, the former uses static generation whilst the latter uses server side rendering. Hmm... ok but do I need page pre-rendering?
Next.JS is a tool employed primarily to build server-side rendered websites that generate the HTML dynamically through a server during every instance of receiving a new request. Data fetching in Next.js allows you to render your content in different ways, depending on your application’s use case.
But then I read in the Next.js documentation that you should not use fetch () to all an API route in getServerSideProps (). You want to use the logic that's in your API route directly in getServerSideProps, rather than calling your internal API.
This is useful if you want to fetch data that changes often, and have the page update to show the most current data. You can import modules in top-level scope for use in getServerSideProps. Imports used will not be bundled for the client-side.
getInitialProps
is the old way of what you are doing to do. But getServerSideProps
and getStaticProps
will replace getInitialProps
https://nextjs.org/docs/api-reference/data-fetching/getInitialProps
But getServerSideProps
can't be used in _app for global data fetching for now. It will be introduced later. Until then, I think you have these options:
getInitialProps
and trade static optimizationgetServerSideProps
wrapper and a HoC like withMenuItem
and wrap all pages and their getServerSideProps
exports.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With