Skip to content

Instantly share code, notes, and snippets.

@shafiimam
Created December 4, 2021 10:23
Show Gist options
  • Save shafiimam/ab6c80c6e56ea859744bbc36dffaeee9 to your computer and use it in GitHub Desktop.
Save shafiimam/ab6c80c6e56ea859744bbc36dffaeee9 to your computer and use it in GitHub Desktop.
Shopify next js route propagation

Shopify NextJs App Route Propagation

In shopify next js app page are generated in the server and then served to client side. Under the hood next js uses react's routing to dynamically update the browser URL without reloading the page again and again.

To make this work and change the URL without loading the page inside a shopify embedded app's iframe follow these steps

  1. Create a file named RoutePropagator.js.
  2. Paste this code inside RoutePropagator.js
import React from "react";
import Router, { useRouter } from "next/router";
import { Context as AppBridgeContext } from "@shopify/app-bridge-react";
import { Redirect } from "@shopify/app-bridge/actions";
import { RoutePropagator as ShopifyRoutePropagator } from "@shopify/app-bridge-react";

const RoutePropagator = () => {
  const router = useRouter();
  const { route } = router;
  const appBridge = React.useContext(AppBridgeContext);

  // Subscribe to appBridge changes - captures appBridge urls
  // and sends them to Next.js router. Use useEffect hook to
  // load once when component mounted
  useEffect(() => {
    appBridge.subscribe(Redirect.Action.APP, ({ path }) => {
      Router.push(path);
    });
  }, []);

  return appBridge && route ? (
    <ShopifyRoutePropagator location={route} app={appBridge} />
  ) : null;
};

export default RoutePropagator;
  1. Place the RoutePropagator component inside of _app.js's Provide component
class MyApp extends App {
  render() {
    const { Component, pageProps, host } = this.props;
    return (
      <AppProvider i18n={translations}>
        <Provider
          config={{
            apiKey: API_KEY,
            host: host,
            forceRedirect: true,
          }}
        >
          <RoutePropagator/>
          <MyProvider Component={Component} {...pageProps} />
        </Provider>
      </AppProvider>
    );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment