Shopify App Bridge | ReferenceError: shopify is not defined

closeddoor
Shopify Partner
1 0 1

I'm building an embedded app using Next.js v12 and Shopify App Bridge CDN (https://cdn.shopify.com/shopifycloud/app-bridge.js). I load the CDN script on the _document.js file, and I'm trying to get the shopify global variable by calling a function like this:

 

 

 

const getShopifyData = async () => {
  const shopifyData = await shopify
  return shopify
}

 

 


I'm able to get the data if I test it using dev environment and make my localhost public by using Cloudflare tunnel. But as soon as I build & set it to production, the code never works and always returning the "ReferenceError: shopify is not defined" error. I have tried some workaround like adding try catch, add some delay / setTimeout before calling the code, also tried to call it from getInitialProps / useEffect. But still not able to make it works. Does anyone have a suggestion for this issue I'm facing? 

Thank you in advance.

 

Reply 1 (1)

ConstantineDev
Shopify Partner
9 0 2

You try to use frontend feature in backend. Instead of this you must use it in frontend.

 

const [ app, setApp ] = useState<ClientApplication | null>(null);

useEffect(() => {
const appObject = createApp({
apiKey: shopify.config.apiKey,
host: shopify.config.host || ''
});
setApp(appObject);
}, []);


useEffect
(() => {
if(app) {
const redirect = Redirect.create(app);
redirect.dispatch(Redirect.Action.REMOTE, '/');
}
}, [app])