I have a small next.js project, which is served by an Express.js application. It works by exporting the Next app into static HTML (next export
), and the Express server serves it as static files from a public directory.
Now the problem is, that the Next app has multiple (static) routes (/page1
, /page2
, ...), but nearly all pages need the same data which I fetch from an api (client side).
Now these pages look like:
export default function PageN() {
const [ data, setData ] = useState(null)
useEffect(() => {
fetch(...).then((r) => {
setData(r)
})
}, [])
// ...
if (data) {
// render page
} else {
// render 'loading'
}
}
After loading the app, and navigating from /
to /page1
it fetches the data from an api. But it does that again, if navigate to /page2
. The ideal solution would be fetching the required data somewhere on load, store it globally, and make it available for every page. Maybe in _app.js
. I have tried experimenting with getStaticProps
and getInitialProps
in _app.js
, but I couldn't make it work.
Is there a way to fetch data only once, and share it between every page, but still keep the ability to export the app into static HTML?