next.js: is incorrect

Bug report

Describe the bug

AppTree is sometimes incorrect in this code:

import BaseApp from "next/app";
import { renderToStaticMarkup } from "react-dom/server";

export default class App extends BaseApp {
  static async getInitialProps(appCtx) {
    const initialProps: any = await BaseApp.getInitialProps(appCtx);

    // Not working
    const { AppTree } = appCtx;
    console.log("Wrong", renderToStaticMarkup(<AppTree {...initialProps} />));

    return initialProps;
  }

  render() {
    return <BaseApp {...this.props} />;
  }
}

Therefore, all the “with-apollo” examples don’t work and the “next-with-apollo” package too.

To Reproduce

  1. Open this Code Sand Box : https://codesandbox.io/s/nextjs-apptree-bug-0v2tl
  2. Click on the “About page” link then on the “Home page” link
  3. Click on the console tab. You should see this and observe the current <AppTree /> is sometimes incorrect:
Current <AppTree />: <a href="/about">About page</a> 
Correct <AppTree />: <a href="/">Home page</a> 

Current <AppTree />: <a href="/about">About page</a> 
Correct <AppTree />: <a href="/about">About page</a> 

Current <AppTree />: <a href="/about">About page</a> 
Correct <AppTree />: <a href="/">Home page</a> 

Current workaround

I found a simple way to get the correct AppTree by looking at Next.js source code:

import BaseApp from "next/app";
import { renderToStaticMarkup } from "react-dom/server";

export default class App extends BaseApp {
  static async getInitialProps(appCtx) {
    const initialProps: any = await BaseApp.getInitialProps(appCtx);

    // Working
    const { Component, err, router } = appCtx;
    console.log(
      "Good",
      renderToStaticMarkup(
        <App {...{ Component, err, router }} {...initialProps} />
      )
    );

    return initialProps;
  }

  render() {
    return <BaseApp {...this.props} />;
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 14
  • Comments: 22 (4 by maintainers)

Commits related to this issue

Most upvoted comments

Experiencing the same issue, it might be some combination of AppTree and @apollo/react-ssr v3

This is still an issue and is needed for proper Apollo client SSR. We really need maintainers on this, I don’t think it’s a “good first issue”. SSR is a selling point of Next.js and this not working kinda kills that.

Fyi I was able to work around this issue by writing this getInitialAppProps of my _app, inspired by https://stackoverflow.com/questions/67022296/next-with-apollo-ssr-does-not-work-request-is-done-on-client/67857064#67857064

// _app.tsx

import { ApolloClient, ApolloProvider, NormalizedCacheObject } from "@apollo/client";
import App, { AppContext, AppProps } from "next/app";
import nookies from "nookies";
import React from "react";
import { IntlProvider, MessageFormatElement } from "react-intl";
import createApolloClient, { ApolloClientOptions } from "lib/apollo";

const isServerSide = typeof window === "undefined";

const getCookie = (name: string, ctx?: NextPageContext) =>
  nookies.get(ctx)[name];

type SafeApolloClient = ApolloClient<NormalizedCacheObject> & {
  toJSON?: () => null;
};

type ContextWithApollo = AppContext & {
  apolloClient?: SafeApolloClient;
  apolloState?: NormalizedCacheObject;
};

// On the client, we store the Apollo Client in the following variable.
// This prevents the client from reinitializing between page transitions.
let globalApolloClient: SafeApolloClient = null;

const initOnContext = (context: ContextWithApollo) => {
  const apolloContext = context.ctx;

  // Initialize ApolloClient if not already done
  const apolloClient: SafeApolloClient =
    context.apolloClient ||
    initApolloClient(context.apolloState || {}, {
      ...apolloContext,
      getToken: () => getCookie(AUTH_KEY, apolloContext),
    });

  // We send the Apollo Client as a prop to the component to avoid calling initApollo() twice in the server.
  // Otherwise, the component would have to call initApollo() again but this
  // time without the context. Once that happens, the following code will make sure we send
  // the prop as `null` to the browser.
  apolloClient.toJSON = () => null;

  // Add apolloClient to NextAppContext.
  // This allows us to consume the apolloClient inside our
  // custom `getInitialProps({ apolloClient })`.
  // context.ctx.apolloClient = apolloClient;
  context.apolloClient = apolloClient;

  return context;
};

const initApolloClient = (
  initialState: NormalizedCacheObject,
  options: ApolloClientOptions,
) => {
  // Make sure to create a new client for every server-side request so that data
  // isn't shared between connections (which would be bad)
  if (isServerSide) {
    return createApolloClient(initialState, options);
  }

  // Reuse client on the client-side
  if (!globalApolloClient) {
    globalApolloClient = createApolloClient(initialState, options);
  }

  return globalApolloClient;
};

const useAppApolloClient = (
  apolloClient?: SafeApolloClient,
  apolloState?: NormalizedCacheObject,
) =>
  // apolloClient is defined if called from getDataFromTree or from Next.js SSR
  apolloClient ||
  initApolloClient(apolloState, { getToken: () => getCookie(AUTH_KEY) });

type Props = AppProps & {
  apolloClient?: SafeApolloClient;
  apolloState?: NormalizedCacheObject;
  messages: Record<string, MessageFormatElement[]>;
};

const MyApp = ({
  Component,
  pageProps,
  messages,
  apolloClient,
  apolloState,
  router,
}: Props) => {
  const client = useAppApolloClient(apolloClient, apolloState);

  return (
    <ApolloProvider client={client}>
      <IntlProvider
        locale={router.locale}
        defaultLocale={router.defaultLocale}
        messages={messages}
      >
        <SomeProvider>
          <Component {...pageProps} />
        </SomeProvider>
      </IntlProvider>
    </ApolloProvider>
  );
};

MyApp.getInitialProps = async (context: ContextWithApollo) => {
  const { router, AppTree, ctx } = context;

  const { apolloClient } = initOnContext(context);

  const pageProps = await App.getInitialProps(context);

  // Messages are needed for CSR, SSR & AppTree
  const lang = router.locale || router.defaultLocale;
  const messages = require(`../../lang/${lang}.ast.json`);

  if (isServerSide) {
    // tell the browser to cache for 5 minutes
    // tell the CDN to:
    // - cache for 1 minute
    // - after 1 minute, keep serving cache but regenerate in background (SWR)
    // - if older than 1 hour, regenerate then serve fresh version (SSR)
    ctx.res?.setHeader(
      "cache-control",
      "max-age=300, s-maxage=60, stale-while-revalidate=3600",
    );

    if (AppTree) {
      // Only if dataFromTree is enabled
      try {
        // Import `@apollo/react-ssr` dynamically.
        // We don't want to have this in our client bundle.
        const { getDataFromTree } = await import("@apollo/client/react/ssr");

        const treeProps = { ...pageProps, messages, apolloClient };

        // Take the Next.js AppTree, determine which queries are needed to render,
        // and fetch them. This method can be pretty slow since it renders
        // your entire AppTree once for every query. Check out apollo fragments
        // if you want to reduce the number of rerenders.
        // https://www.apollographql.com/docs/react/data/fragments/
        await getDataFromTree(<AppTree {...treeProps} />);
      } catch (error) {
        // Prevent Apollo Client GraphQL errors from crashing SSR.
        // Handle them in components via the data.error prop:
        // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
        console.error("Error while running `getDataFromTree`", error);
      }
    }
  }

  return {
    ...pageProps,
    messages,
    // Extract query data from the Apollo store
    apolloState: apolloClient.cache.extract(),
    // Provide the client for ssr. As soon as this payload
    // gets JSON.stringified it will remove itself.
    apolloClient: context.apolloClient,
  };
};

export default MyApp;

To who it may concern, I put in PR #23721 to fix this.

Really hoping it will be merged so that we can use AppTree to preload data for pages on client-side too! IMO half the reason for SSR is so that users don’t see a bunch of initial “loading” indicators when they open a page… But why bother with that optimization if the user will see those initial “loading” indicators when navigating within the site anyways? I guess just for SEO?

Any news on this?

The workaround doesn’t fully work because the app is not wrapped (in the Next.js source code, app is passed to a wrapApp function that adds router, etc…).

Hence, useRouter returns null.

When trying to use Apollo’s getDataFromTree, it crashes with a TypeError: Cannot convert undefined or null to object, and the error comes from renderToStaticMarkup. Although I can’t figure out what is wrong with the rendering of that AppTree, it should definitely be compatible with React SSR render functions, to populate Apollo cache from Next SSR.

Note that I tried to implement https://github.com/shshaw/next-apollo-ssr but it just doesn’t work with my components tree.

@Timer Any updates?