Search code examples
javascriptnext.jsmiddlewarereact-context

Next.js pass dynamically loaded server-side data available to all components


(I'm new to Next.js, and I took over a project that was written with it, so excuse if this is something obvious that I'm not seeing)

I have some data that I need to load server-side each request. It was written in getServerSideProps and was working just fine for one page. However now I need to have many pages, with many reused components between them down the component tree. I need a mechanism to have a globally available variable that I can access from each component, and that variable needs to be populated at server side. Repeating same code over and over in getServerSideProps and passing all the data downstream via props is too cumbersome and redundant, I need a centralized/static/hook(y) approach.

I'm doing the API call at middleware.js at request time and get the required data. How do I provide that data to all components down the tree? If it was purely client side, I'd have used a Context/store, yet I couldn't figure out how to pass data at server to client components.


Solution

  • I've ended up using App.getInitialProps to fetch the needed data, pass it to my custom App component there as a prop. The rest is trivial in React side: wrapping the app in a context provider that I created with the value read from app props, and used a hook that I wrote to access the data wherever I need.