next/app#AppInitialProps TypeScript Examples

The following examples show how to use next/app#AppInitialProps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fetchAppData.ts    From next-page-tester with MIT License 6 votes vote down vote up
export default async function fetchAppData({
  pageObject,
  options,
}: {
  pageObject: PageObject;
  options: ExtendedOptions;
}): Promise<AppInitialProps | undefined> {
  const { env } = options;
  const { files } = pageObject;
  const AppComponent = files[env].appFile.default;

  const { getInitialProps } = AppComponent;
  if (getInitialProps) {
    const { asPath, pathname, query, route, basePath } = makeRouterMock({
      options,
      pageObject,
    });

    const ctx: AppContext = {
      // @NOTE AppTree is currently just a stub
      AppTree: Fragment,
      Component: pageObject.files.client.pageFile.default,
      ctx: makeGetInitialPropsContext({ pageObject, options }),
      // @ts-expect-error incomplete router object
      router: { asPath, pathname, query, route, basePath },
    };

    const appInitialProps =
      env === RuntimeEnvironment.SERVER
        ? await executeAsIfOnServer(() => getInitialProps(ctx))
        : await getInitialProps(ctx);

    return appInitialProps;
  }
}
Example #2
Source File: fetchPageData.ts    From next-page-tester with MIT License 6 votes vote down vote up
function mergePageDataWithAppData({
  pageData,
  appInitialProps,
}: {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  pageData: { [key: string]: any };
  appInitialProps?: AppInitialProps;
}) {
  const { props: pageProps, ...restOfPageData } = pageData;
  const { pageProps: appPageProps, ...restOfAppInitialProps } =
    appInitialProps || {};
  //appInitialProps.pageProps gets merged with pageData.props
  return {
    props: {
      ...appPageProps,
      ...pageProps,
    },
    appProps: <PageProps>restOfAppInitialProps,
    ...restOfPageData,
  };
}
Example #3
Source File: _app.tsx    From storefront with MIT License 5 votes vote down vote up
App: NextComponentType<AppContext, AppInitialProps, Props> = ({
  apollo,
  apolloState,
  Component,
  pageProps,
  router,
}) => {
  useMount(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    jssStyles?.parentNode?.removeChild(jssStyles);

    ReactGA.initialize(process.env.GA_TRACKING_ID, {
      debug: process.env.NODE_ENV === 'development',
    });
    ReactGA.plugin.require('ec');
    ReactGA.pageview(router.asPath);

    router.events.on('routeChangeComplete', (url: string) => {
      ReactGA.pageview(url);
    });
  });

  return (
    <ApolloProvider client={apollo ?? createClient({ initialState: apolloState?.data })}>
      <SettingsProvider>
        <SettingsContext.Consumer>
          {({ settings, seo }) => (
            <>
              <Head>
                <meta
                  name="viewport"
                  content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
                />
                {seo.webmaster?.googleVerify != null && (
                  <meta name="google-site-verification" content={seo.webmaster.googleVerify} />
                )}
                {seo.webmaster?.msVerify != null && (
                  <meta name="msvalidate.01" content={seo.webmaster.msVerify} />
                )}
              </Head>
              <DefaultSeo
                title={settings.title ?? undefined}
                description={settings.description ?? undefined}
                canonical={absoluteURL(router.asPath)}
                openGraph={{
                  type: 'website',
                  locale: 'en_US',
                  url: absoluteURL(router.asPath),
                  site_name: settings.title ?? undefined,
                }}
                twitter={{
                  handle: '@artwithaliens',
                  cardType: 'summary_large_image',
                }}
              />
            </>
          )}
        </SettingsContext.Consumer>
        <ManagedUIContext>
          <CssBaseline />
          <Component {...pageProps} />
        </ManagedUIContext>
      </SettingsProvider>
    </ApolloProvider>
  );
}
Example #4
Source File: DefaultApp.tsx    From next-page-tester with MIT License 5 votes vote down vote up
DefaultApp: React.FC<Props> & {
  getInitialProps?: (appContext: AppContext) => Promise<AppInitialProps>;
} = function DefaultApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}
Example #5
Source File: fetchPageData.ts    From next-page-tester with MIT License 4 votes vote down vote up
/*
 * fetchPageData behaves differently depending on whether custom /_app
 * fetches data or not (appInitialProps)
 *
 * /_app HAS NOT fetched data:
 * fetch page data using the first available method:
 * - getInitialProps
 * - getServerSideProps
 * - getStaticProps
 *
 * /_app HAS fetched data:
 * DO NOT call getInitialProps, if available
 * If available, call getServerSideProps or getServerSideProps
 * and merge returned object's prop property with appInitialProps.pageProps
 *
 * If no fetching methods available, return appInitialProps.pageProps as {props: appInitialProps.pageProp}
 */
export default async function fetchPageData({
  pageObject,
  appInitialProps,
  options,
}: {
  pageObject: PageObject;
  appInitialProps?: AppInitialProps;
  options: ExtendedOptions;
}): Promise<PageData> {
  const { env } = options;
  const { files } = pageObject;
  const pageFile = files[env].pageFile;
  ensureNoMultipleDataFetchingMethods({ page: pageFile });

  const pageComponent = pageFile.default;
  const { getInitialProps } = pageComponent;
  if (
    getInitialProps &&
    // getInitialProps is not called when custom App has the same method
    !appInitialProps
  ) {
    const ctx: NextPageContext = makeGetInitialPropsContext({
      options,
      pageObject,
    });

    if (env === RuntimeEnvironment.CLIENT) {
      const initialProps = await getInitialProps(ctx);
      return { props: initialProps };
    } else {
      const initialProps = await executeAsIfOnServer(() =>
        getInitialProps(ctx)
      );
      return { props: initialProps };
    }
  }

  // Data fetching methods available to actual pages only
  if (pageObject.type === 'found') {
    const { files, params } = pageObject;
    const serverPageFile = files.server.pageFile;
    if (serverPageFile.getServerSideProps) {
      const { getServerSideProps } = serverPageFile;
      const ctx: GetServerSidePropsContext<
        typeof params
      > = makeGetServerSidePropsContext({ options, pageObject });
      const pageData = await executeAsIfOnServer(() => getServerSideProps(ctx));
      ensurePageDataHasProps({ pageData });
      return mergePageDataWithAppData({ pageData, appInitialProps });
    }

    if (serverPageFile.getStaticProps) {
      const { getStaticProps } = serverPageFile;
      const ctx: GetStaticPropsContext<typeof params> = makeStaticPropsContext({
        pageObject,
      });
      // @TODO introduce `getStaticPaths` logic
      // https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation
      const pageData = await executeAsIfOnServer(() => getStaticProps(ctx));
      ensurePageDataHasProps({ pageData });
      return mergePageDataWithAppData({ pageData, appInitialProps });
    }

    if (appInitialProps) {
      const { pageProps, ...restOfAppInitialProps } = appInitialProps;
      return { props: pageProps, appProps: <PageProps>restOfAppInitialProps };
    }
  }

  return {};
}