0

(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.

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • Maybe you should look into ["Context API"](https://reactjs.org/docs/context.html) or Redux? – Vladimir Jovanović Aug 20 '22 at 10:38
  • @VladimirJovanović as I've already stated clearly in the question: 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. – Can Poyrazoğlu Aug 20 '22 at 11:17
  • [The data you return from the `getServerSideProps` function](https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props) is available to a page component via prop(s). You can then streamline the data to other components via the "Context API" or Redux. – Vladimir Jovanović Aug 20 '22 at 16:37
  • @VladimirJovanović as I've already stated clearly in the question: Repeating same code over and over in getServerSideProps and passing all the data downstream via props is too cumbersome and redundant. – Can Poyrazoğlu Aug 20 '22 at 20:08
  • You can create a re-usable function that you'd call on each `getServerSideProps`, you don't necessarily have to duplicate code. – juliomalves Aug 21 '22 at 11:44
  • Does this answer your question? [Retrieve data server side and save in context with Next.js](https://stackoverflow.com/questions/66106408/retrieve-data-server-side-and-save-in-context-with-next-js) – Eric Burel Feb 22 '23 at 16:04

1 Answers1

0

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.

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389