2

We have a simple setup involving a Context API provider wrapping the _app.tsx page. The flow we're trying to implement is:

  1. On a page we collect some data from an API by using getServerSideProps
  2. We send the data to the page through the props
  3. We update the context from the page (the context provider is wrapping the _app.tsx as mentioned above)
  4. The context is updated and all the children components can access the data in it

So we have a pretty standard setup that works correctly on the client side. The problem is that the updated context values are not being used to SSR the pages.

Context API

const ContextValue = createContext();
const ContextUpdate = createContext();

export const ContextProvider = ({children}) => {
  const [context, setContext] = useState({});
  
  return <ContextValue.Provider value={context}>
    <ContextUpdate.Provider value={setContext}>
      {children}
    </ContextValue.Provider>
  </ContextUpdate.Provider>
}

export const useContextValue = () => {
  const context = useContext(ContextValue);
  return context;
}

export const useContextUpdate = () => {
  const update = useContext(ContextUpdate);
  return update;
}

Then we have on _app.jsx:

...
return <ContextProvider>
  <ContextApiConsumingComponent />
  <Component {...pageProps} />
</Context>

And in any page, if we can update the context by using the hook provided above. For example:

export function Index({customData, isSSR}) {
  const update = useContextUpdate();

  if(isSSR) {
    update({customData})
  }
  return (
    <div>...</div>
  );
}

export async function getServerSideProps(context) {
  ...

  return {
      props: { customData , isSSR}
  };
};

And we can consume the context in our ContextApiConsumingComponent:

export function ContextApiConsumingComponent() {
  const context = useContextValue()

  return <pre>{JSON.stringify(context?.customData ?? {})}</pre>
}

The (very simplified) code above works fine on the client. But during the SSR, if we inspect the HTML sent to the browser by the server, we'll notice that the <pre></pre> tags are empty even though the context values are correctly sent to the browser in the __NEXT_DATA__ script section (they are precisely filled with the data on the browser after the app is loaded).

I've put together a GitHub repo with a minimum reproduction too.

Am I missing something?

3
  • What value are you returning in isSSR? How is that variable defined? You should also not call a state setter function (setContext via update) directly from render, call it inside a useEffect. Commented Jul 6, 2022 at 17:42
  • It's defined like this: const isSSR = !context?.req?.url?.includes('_next/'). The update cannot be called from a useEffect because I wanted it to be executed during the server-side rendering. I can add more logic to make this happen only on the server-side though. Commented Jul 7, 2022 at 14:29
  • There's a repo with a minimum reproduction here: github.com/julianobrasil/next-js-issue Commented Jul 7, 2022 at 14:33

2 Answers 2

2

As far as I understand, React doesn't wait for asynchronous actions to be performed during the SSR. Whereas setState is an asynchronous operation.

If you want it to be rendered during SSR, you need to provide an initialValue for useState hook.

export const ContextProvider = ({children, customData}) => {
  const [context, setContext] = useState(customData);
  
  // ...
}
3
  • It makes sense... Almost all the frameworks SSR synchronously (Qwik is an exception AFAIK). I'll do some tests, because I don't know the customData in advance to initialize it. Probably going to use a global variable during the SSR. Commented Jul 7, 2022 at 16:54
  • You can move the logic of fetching the customData to _app.ts and then pass customData to ContextProvider to use it as an initial value. This document may be helpful Commented Jul 7, 2022 at 21:25
  • My first attempt was using getInitialProps, but the fact that it's executed once on the server and once on the client didn't help. It's there a pattern to work that around elegantly? I tend to think, again, of a global variable as a solution. I'll check the link you posted, thanks. Commented Jul 8, 2022 at 8:17
1

Not sure if you have other reasons for using the context to get this data into the api consumer but with nextjs, the getStaticProps or getServerSideProps of course feeds into the route component, but maybe you've missed the following detail?

The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.

pageProps is an object with the initial props that were preloaded for your page by one of our data fetching methods, otherwise it's an empty object.

https://nextjs.org/docs/advanced-features/custom-app

Therefore the _app.tsx can act on any props your route components would normally receive from getStaticProps or getServerSideProps

types.ts


// or whatever union type you need to indicate that myriad of "custom datas" you might be pushing out of getStaticProps
export type MaybeCustomDataFromGetStaticProps = Map<string, string> | undefined;

export type PagePropsWithCustomData = {
  customData: MaybeCustomDataFromGetStaticProps
  isSSR?: boolean;
}

pages/_app.tsx

import type { PagePropsWithCustomData } from '../types';

const App = ({
  Component,
  pageProps: { customData, isSSR, ...pageProps},
  router,
}: AppProps<PagePropsWithCustomData & Record<string, unknown>>) => {

  return (
    <ContextProvider value={{ isSSR, customData }}>
      <ContextApiConsumingComponent />
      <Component {...pageProps} />
    </ContextProvider>
  )

}

pages/somepage.tsx

import type { NextPage, GetServerSideProps } from "next";
import type { PagePropsWithCustomData } from '../types';
import { magicallyGetCustomData } from '../services/Api';
import { isSSR } from '../core/Routing';

type IndexRouteProps = PagePropsWithCustomData & {
  isSSR?: boolean;
}

const IndexRoute:NextPage<IndexRouteProps> = ({ customData, isSSR }) => {

  // no longer need to do anything with customData, or isSSR here

  return (
    <div>stuff</div>
  );
}

export const getServerSideProps:GetServerSideProps<IndexRouteProps> = async (context) => {
  const customData = await magicallyGetCustomData();
  
  return {
      props: { customData , isSSR: isSSR(context) }
  };
};

export default IndexRoute
5
  • The problem is that I don't get the context values durung the server side rendering. Which means, in my specific case, that the HTML I send to the browser during the first load is useless from the POV of SEO. I provide more details on this GitHub issue: github.com/vercel/next.js/issues/38332 Commented Mar 5, 2023 at 11:16
  • 1
    @julianobrasil I'm currently doing the above and my magicallyGetCustomData is called serverside and when i run a SSG build, so i end up with my context filled with the data i expect it to have. So it's strange that you're not. Have you done some breakpoints serverside to confirm that?
    – airtonix
    Commented Mar 5, 2023 at 11:32
  • On the github link I left above, there's a link to a repo with the reproduction of the issue: github.com/julianobrasil/next-js-issue. I guess the difference is the fact that you're initializing the context with the data instead of updating it later on in the component, right? Commented Mar 6, 2023 at 0:00
  • As this question was asked a while ago, I'd have to take a look at the project I was working on at that time to see what exactly I was trying to do. I can see your point and I don't remember exactly why I couldn't do that. Maybe it was because I was learning Next.js... or maybe I had a restriction I currently don't remember anymore :) Commented Mar 6, 2023 at 0:09
  • @julianobrasil yeah my first thought was that maybe you did this back when there were other things preventing you from doing it the above way? I also never have a need to send data back up the tree due to using things like redux or mobx anymore since apolloClient and reactQuery replace that concept for me. I think it's worth examining it again, since this page comes up in google results for "nextjs ssr context empty" (it will now lol)
    – airtonix
    Commented Mar 6, 2023 at 2:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.