next/app#AppContext TypeScript Examples

The following examples show how to use next/app#AppContext. 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: _app.tsx    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
MyApp.getInitialProps = async (context: AppContext) => {
  const appProps = await App.getInitialProps(context);

  const cookies = cookie.parse(
    context.ctx.req ? context.ctx.req.headers.cookie || '' : document.cookie,
  );

  return {
    ...appProps,
    cookies,
  };
};
Example #2
Source File: _app.tsx    From compose-starter-helpcenter-nextjs with MIT License 6 votes vote down vote up
HelpdeskApp.getInitialProps = async (appContext: AppContext) => {
  const { pageProps, ...other } = await App.getInitialProps(appContext);
  const locale = getLocale(appContext.ctx.query.locale);

  switch (locale) {
    case UnknownLocale:
      appContext.ctx.res.writeHead(302, { Location: '/' }).end();
      break;
    case undefined:
      return { pageProps, ...other };
    default:
      return { pageProps: { ...pageProps, locale }, ...other };
  }
};
Example #3
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 #4
Source File: loadPageLocale.ts    From rcvr-app with GNU Affero General Public License v3.0 6 votes vote down vote up
async function loadPageLocale(
  props: AppContext
): Promise<Partial<LocaleContextProps>> {
  const locale = props.router.locale
  const { pathname } = props.ctx

  if (config[pathname]) {
    const path = pathname as keyof typeof config

    const { locales, namespace } = config[path]

    const lang = (
      locales.includes(locale)
        ? locale
        : locales.includes(props.router.defaultLocale)
        ? props.router.defaultLocale
        : locales[0]
    ) as SupportedLanguage

    if (process.env.NODE_ENV !== 'production') {
      console.info('[locale] loading lang "%s" for "%s"', lang, pathname)
    }

    const values = await import(`../pages/${namespace}.${lang}.ts`).then(
      (m) => m.default
    )
    return { values, lang, pageLocales: locales }
  } else {
    console.info('[locale] "%s" not found for "%s"', locale, pathname)
    return {}
  }
}
Example #5
Source File: _app.tsx    From rcvr-app with GNU Affero General Public License v3.0 6 votes vote down vote up
RecoverApp.getInitialProps = async (ctx: AppContext) => {
  const { pageProps, ...rest } = await App.getInitialProps(ctx)

  const localeContext = await loadPageLocale(ctx)

  return {
    ...rest,
    pageProps: {
      ...pageProps,
      localeContext,
    },
  }
}
Example #6
Source File: _app.tsx    From Demae with MIT License 5 votes vote down vote up
App.getInitialProps = async (context: AppContext) => {
	const appProps = await NextApp.getInitialProps(context);
	return { ...appProps };
}
Example #7
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 #8
Source File: _app.tsx    From core with GNU Affero General Public License v3.0 5 votes vote down vote up
KoreanbotsApp.getInitialProps = async (appCtx: AppContext) => {
	const appProps = await App.getInitialProps(appCtx)
	const parsed = parseCookie(appCtx.ctx.req)
	return {
		...appProps,
		cookie: parsed
	}
}
Example #9
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 #10
Source File: _app.tsx    From slice-machine with Apache License 2.0 5 votes vote down vote up
function MyApp({ Component, pageProps }: AppContext & AppInitialProps) {
  const [serverState, setServerState] = useState<ServerState | null>(null);
  const [smStore, setSMStore] = useState<{
    store: Store;
    persistor: Persistor;
  } | null>(null);

  useEffect(() => {
    async function getInitialState() {
      const { data: serverState } = await getState();
      setServerState(serverState);
    }
    void getInitialState();
  }, []);

  useEffect(() => {
    if (!serverState) {
      return;
    }

    const normalizedCustomTypes = normalizeFrontendCustomTypes(
      serverState.customTypes,
      serverState.remoteCustomTypes
    );

    const { store, persistor } = configureStore({
      environment: serverState.env,
      availableCustomTypes: {
        ...normalizedCustomTypes,
      },
      slices: {
        libraries: serverState.libraries,
        remoteSlices: serverState.remoteSlices,
      },
    });

    const state = store.getState();
    const tracking = getIsTrackingAvailable(state);
    const repoName = getRepoName(state);

    Tracker.get().initialize(
      process.env.NEXT_PUBLIC_SM_UI_SEGMENT_KEY ||
        "Ng5oKJHCGpSWplZ9ymB7Pu7rm0sTDeiG",
      repoName,
      tracking
    );

    setSMStore({ store, persistor });
  }, [serverState]);

  return (
    <>
      <Head>
        <title>SliceMachine</title>
      </Head>
      <ThemeProvider theme={theme}>
        <BaseStyles>
          <RemoveDarkMode>
            {!smStore || !serverState ? (
              <LoadingPage />
            ) : (
              <Provider store={smStore.store}>
                <ConnectedRouter>
                  <PersistGate loading={null} persistor={smStore.persistor}>
                    <SliceMachineApp>
                      <Component {...pageProps} />
                    </SliceMachineApp>
                  </PersistGate>
                </ConnectedRouter>
              </Provider>
            )}
          </RemoveDarkMode>
        </BaseStyles>
      </ThemeProvider>
    </>
  );
}
Example #11
Source File: _app.tsx    From slice-machine with Apache License 2.0 5 votes vote down vote up
MyApp.getInitialProps = async (appContext: AppContext) => {
  return await App.getInitialProps(appContext);
};
Example #12
Source File: App.tsx    From solana-pay with Apache License 2.0 5 votes vote down vote up
App: FC<AppProps> & { getInitialProps(appContext: AppContext): Promise<AppInitialProps> } = ({
    Component,
    host,
    query,
    pageProps,
}) => {
    const baseURL = `https://${host}`;

    // If you're testing without a mobile wallet, set this to true to allow a browser wallet to be used.
    const connectWallet = false;
    const network = WalletAdapterNetwork.Devnet;
    const wallets = useMemo(
        () => (connectWallet ? [new PhantomWalletAdapter(), new SolflareWalletAdapter({ network })] : []),
        [connectWallet, network]
    );

    // Toggle comments on these lines to use transaction requests instead of transfer requests.
    const link = undefined;
    // const link = useMemo(() => new URL(`${baseURL}/api/`), [baseURL]);

    let recipient: PublicKey | undefined = undefined;
    const { recipient: recipientParam, label, message } = query;
    if (recipientParam && label) {
        try {
            recipient = new PublicKey(recipientParam);
        } catch (error) {
            console.error(error);
        }
    }

    return (
        <ThemeProvider>
            <FullscreenProvider>
                {recipient && label ? (
                    <ConnectionProvider endpoint={DEVNET_ENDPOINT}>
                        <WalletProvider wallets={wallets} autoConnect={connectWallet}>
                            <WalletModalProvider>
                                <ConfigProvider
                                    baseURL={baseURL}
                                    link={link}
                                    recipient={recipient}
                                    label={label}
                                    message={message}
                                    symbol="SOL"
                                    icon={<SOLIcon />}
                                    decimals={9}
                                    minDecimals={1}
                                    connectWallet={connectWallet}
                                >
                                    <TransactionsProvider>
                                        <PaymentProvider>
                                            <Component {...pageProps} />
                                        </PaymentProvider>
                                    </TransactionsProvider>
                                </ConfigProvider>
                            </WalletModalProvider>
                        </WalletProvider>
                    </ConnectionProvider>
                ) : (
                    <div className={css.logo}>
                        <SolanaPayLogo width={240} height={88} />
                    </div>
                )}
            </FullscreenProvider>
        </ThemeProvider>
    );
}