1

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

6
  • Maybe you should look into "Context API" or Redux? Commented Aug 20, 2022 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. Commented Aug 20, 2022 at 11:17
  • The data you return from the getServerSideProps function is available to a page component via prop(s). You can then streamline the data to other components via the "Context API" or Redux. Commented Aug 20, 2022 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. Commented Aug 20, 2022 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. Commented Aug 21, 2022 at 11:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Big caveat is that with this solution any context consumer is automatically a client component whereas prop drilling will guarantee they are rendered on the server
@DannyMoshe yup, this is not the best approach, I agree. while it solved my problem it also causes many problems with SSR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.