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
- Create a file named
RoutePropagator.js
. - 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;
- 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>
);
}
}