How to remove `getInitialProps` from the Next.js application made by shopify-app-node

We can easy to create a new own Next.js application for the Shopify app by using shopify-app-node and Shopify […]

広告ここから
広告ここまで

目次

    We can easy to create a new own Next.js application for the Shopify app by using shopify-app-node and Shopify App CLI.
    But, the template is a little bit legacy comparing to the Next.js standard.

    For example, the template is using getInitialProps to get the host data from the query string. But the function is deprecated in Next.js 9.3 or newer.

    So, in this post, show how to remove the getInitialProps function and how can we get the data instead of this function.

    Before

    import { AppProvider } from "@shopify/polaris";
    import { Provider } from "@shopify/app-bridge-react";
    import "@shopify/polaris/dist/styles.css";
    import translations from "@shopify/polaris/locales/en.json";
    
    class MyApp extends App {
      render() {
        const { Component, pageProps, host } = this.props;
        return (
          <AppProvider i18n={translations}>
            <Provider
              config={{
                apiKey: API_KEY,
                host: host,
                forceRedirect: true,
              }}
            >
              <MyProvider Component={Component} {...pageProps} />
            </Provider>
          </AppProvider>
        );
      }
    }
    
    MyApp.getInitialProps = async ({ ctx }) => {
      return {
        host: ctx.query.host,
      };
    };
    
    export default MyApp;

    After

    Using useRouter function, we can get the query string from the URL.

    So we can get the host attributes by using this function.

    import { AppProvider } from "@shopify/polaris";
    import { Provider } from "@shopify/app-bridge-react";
    import { useRouter } from 'next/router'
    import "@shopify/polaris/dist/styles.css";
    import translations from "@shopify/polaris/locales/en.json";
    
    function MyApp({ Component, pageProps, ...props }: AppProps) {
      const { query: { host } } = useRouter()
    
      return (
        <AppProvider i18n={translations}>
          <Provider
            config={{
              apiKey: process.env.NEXT_PUBLIC_SHOPIFY_API_KEY as string,
              host,
              forceRedirect: true
            }}>
            <Component {...pageProps} />
          </Provider>
        </AppProvider>
      )
    }
    
    export default MyApp
    

    TypeScript option

    The host attributes from useRouter will be union type like string | string[] | undefined. But the Provider component allows only string type.

    So we need to handle the props like this.

      const {
        query
      } = useRouter()
      const host = Array.isArray(query.host) ? query.host[0] :query.host || ''

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark