Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Shopify App Bridge not working with React

Shopify App Bridge not working with React

charliehe
Shopify Partner
2 0 1

I am trying to use a React single-page application as the embedded UI for my Shopify app. I've followed the guides on https://shopify.dev/docs/apps/tools/cli to link my Shopify app and set direct API access to online in my shopify.app.toml file. I've also ensured that my app configuration has been deployed.

Unfortunately, when I deploy my React app to shopify.mydomain.com, the React app loads in the embedded UI on my test store, but I get the following errors in console in the embedded UI when trying to access the shopify global variable or try to fetch any Shopify API endpoint. 

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('<URL>') does not match the recipient window's origin ('<URL>').
index-8r6ap7z6.js:41 

Fetch API cannot load shopify:admin/api/graphql.json. URL scheme "shopify" is not supported.
j_ @ index-8r6ap7z6.js:41
(anonymous) @ index-8r6ap7z6.js:49
(anonymous) @ index-8r6ap7z6.js:49
va @ index-8r6ap7z6.js:40
rn @ index-8r6ap7z6.js:40
Vf @ index-8r6ap7z6.js:40
gr @ index-8r6ap7z6.js:38
kh @ index-8r6ap7z6.js:40
hr @ index-8r6ap7z6.js:40
T0 @ index-8r6ap7z6.js:40
T @ index-8r6ap7z6.js:25
N @ index-8r6ap7z6.js:25
index-8r6ap7z6.js:49 

TypeError: Failed to fetch
    at j_ (index-8r6ap7z6.js:41:133624)
    at index-8r6ap7z6.js:49:205
    at index-8r6ap7z6.js:49:226
    at va (index-8r6ap7z6.js:40:24263)
    at rn (index-8r6ap7z6.js:40:42287)
    at Vf (index-8r6ap7z6.js:40:36553)
    at gr (index-8r6ap7z6.js:38:3274)
    at kh (index-8r6ap7z6.js:40:41193)
    at hr (index-8r6ap7z6.js:40:40191)
    at T0 (index-8r6ap7z6.js:40:35664)
index-8r6ap7z6.js:49 

null

 

Here's my React component:

import { useEffect } from "react";

import { Loading, Provider } from "@shopify/app-bridge-react";
import { AppProvider, Card } from "@shopify/polaris";

const config = {
  apiKey: "c795d90d920207874dcf902bdfc422d3",
  host: new URLSearchParams(location.search).get("host") as string,
  forceRedirect: true,
};

const getDomain = async () => {
  try {
    const response = await fetch("shopify:admin/api/graphql.json", {
      method: "POST",
      body: JSON.stringify({
        query: `
        query {
          shop {
            domains {
              host
            }
          }
        }
      `,
      }),
    });

    const {
      shop: { domains },
    }: {
      shop: { domains: { host: string }[] };
    } = await response.json();

    return domains.find(({ host }) => !host.includes(".myshopify.com"));
  } catch (error) {
    console.log(error);

    return null;
  }
};

export default function App() {
  useEffect(() => {
    const initialize = async () => {
      console.log(shopify);
      const domain = await getDomain();
      console.log(domain);
    };

    initialize();
  });

  return (
    <AppProvider i18n={[]}>
      <Provider config={config}>
        <Loading />
        <Card />
      </Provider>
    </AppProvider>
  );
}


I've followed these guides and I cannot for the life of me find any more documentation...

Am I doing something wrong?

 

Replies 20 (20)

Liam
Community Manager
3108 344 910

Hi Charliehe,

 

This does seem like an unusual error - I've connected with the App Bridge team on this and will report back asap.

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

Liam
Community Manager
3108 344 910

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

Fabien_Sebban
Shopify Partner
45 0 21

Hi @Liam 

This app example is a React-embedded app. This means he already loaded the npm package @shopify/app-bridge-react. The app-bridge.js shouldn't be included in the @shopify/app-bridge-react npm package?

Thanks

 

Fabien_Sebban
Shopify Partner
45 0 21

The alert caution message in the app bridge documentation made me think there was probably something wrong with the way I installed the app bridge library in my code. 

Capture d’écran 2024-02-14 à 18.14.32.png

Then, I added the script and meta tags:
<meta name="shopify-api-key" content="SHOPIFY_API_KEY" />
 
But the error persists. Does it mean I have to uninstall the shopify app-bridge npm packages?
 
But I still have the error message "Fetch API cannot load shopify:admin/api/graphql.json. URL scheme "shopify" is not supported."
 
 
pklitscher
Shopify Partner
12 0 23

Hey @Liam 

I am experiencing the same. Currently migrating to the latest app bridge and cannot get authenticated fetch to work. 

I have added the shopify-api-key and script to the head of my index.html

<meta name="shopify-api-key" content="<%- apiKey %>" />
<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>

I can confirm that the global shopify object is available and I can launch the new modal using the ui-modal modal element 

 

However, I am getting the same "Fetch API cannot load shopify:admin/api/graphql.json. URL scheme "shopify" is not supported." error and fetch requests to my own endpoints are not being sent with the authorization headers as described here https://shopify.dev/docs/api/app-bridge-library/reference/resource-fetching

Stephen2020
Shopify Partner
21 2 8

Same problem here:

Fetch API cannot load shopify:admin/api/graphql.json. URL scheme "shopify" is not supported.

 

In the documentation at https://shopify.dev/docs/apps/tools/cli/configuration it is suggested to add a section [access.admin] to shopify.app.toml and that the property "embedded_app_direct_api_access" must be set to true:

 

Stephen2020_0-1708536055052.png

 

But that only gives an error when starting "npm run dev":

 

Stephen2020_1-1708536181559.png

 

 

Kharazian
Shopify Partner
6 0 3

I've been working on a project, and I'm encountering a similar issue with the developing code. It seems like I'm not the only one facing this challenge.

Has anyone found a successful solution or workaround for this problem? 

Kharazian
Shopify Partner
6 0 3

I find this information helpful. This guide on upgrading components to Shopify App Bridge 4 seems particularly useful. It says that a context provider, which was previously required, is no longer needed.

 

Replace this:

import {Provider} from '@shopify/app-bridge-react';
return (
   <Provider config={config}>
      <div>My app</div>
   </Provider>
);

 

With this:

return (
   <div>My app</div>
);

 

Now, you don't need the provider in the latest App Bridge React version.

BertrandProvost
Shopify Partner
2 0 6

Hello,

 

I had this error and I was able to fix it by creating a config file shopify.app.toml like described here https://shopify.dev/docs/apps/tools/cli/configuration with the following config for access.admin

[access.admin]
direct_api_mode = "online"
embedded_app_direct_api_access = true

and then deploying it with (in the same folder):

shopify app deploy

I also had to add those lines to load app-bridge.js

<meta name="shopify-api-key" content="ClientId"/>
<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
Kharazian
Shopify Partner
6 0 3

Hello @BertrandProvost,

 

Can you tell me which framework you utilize (Remix, Next.js, or React)? Additionally, are you able to specify the version of the @shopify/app-bridge-react library you currently use?

 

Thanks!

BertrandProvost
Shopify Partner
2 0 6

React with those packages:

"@shopify/app-bridge-react": "^4.1.1",
"@shopify/polaris": "^12.21.0",
"@shopify/polaris-icons": "^8.8.0",
"@shopify/theme-currency": "^4.1.1",

And in dev deps:

"@shopify/app-bridge-types": "^0.0.9",
Kharazian
Shopify Partner
6 0 3

Thanks, I checked it with Remix, and unfortunately the issues still exist.

Dugani
Shopify Partner
12 0 5

Im still experiencing the same problem did you manage to fix it?

ScalaApps
Shopify Partner
79 3 15

I can't also make this work. I don't think there's any reason you would need app-bridge-react to make this work as well.

Scala Apps



- If you find my reply helpful, please hit Like and Mark as Solution

- Se você achar minha resposta útil, por favor clique em Curtir e Marcar como Solução

Parcelamento/Installments | Hide sold variants | Apps | Blog
ScalaApps
Shopify Partner
79 3 15

I'm pretty sure I did nothing different and is now working. Maybe you have to wait 24 hours after you enable the direct mode api in the toml file.

Scala Apps



- If you find my reply helpful, please hit Like and Mark as Solution

- Se você achar minha resposta útil, por favor clique em Curtir e Marcar como Solução

Parcelamento/Installments | Hide sold variants | Apps | Blog
will-deines
Shopify Partner
4 0 0

For anyone still seeing this issue in Remix, try accessing the GraphQL client directly from the admin api, deconstructed from an authenticate request,  rather than constructing a GraphQL client and using fetch to access shopify:admin/api/graphql.json.

 

This method does not require any changes to your admin.access in the app TOML.

 

Here's a code snippet:

 

export const loader = async ({ request }: LoaderFunctionArgs) => {
// Authenticate the admin user and retrieve billing and session information
const { session, admin } = await authenticate.admin(request);

// Ensure session is available if it is an authenticated route
if (!session) {
throw new Response("Unauthorized", { status: 401 });
}

// For example, retrieve the launchUrl from Shopify
let launchUrl: string;
try {
const response = await admin.graphql(
`#graphql
query {
currentAppInstallation {
launchUrl
}
}`
);

farid-movsumov
Shopify Partner
120 6 37

Thanks for the fix, the following line (shopify.app.toml) fixed problem for me 

 

[access.admin]
embedded_app_direct_api_access = true

CapitalCastle
Shopify Partner
11 1 3

Hello,

I did off to "Development store preview" and then direct api is working.

App => Extensions

スクリーンショット 2024-05-15 10.32.12.png 

 

I hope it will work for everyone.

FA-vuongnq
Shopify Partner
3 0 1

Great job. You had save my times 😍. I hope shopify document will be add this note 😁

Joe47
Shopify Partner
61 8 21

None of these solutions worked for me either. But I was able to get it working by adding the header myself:

 

fetch(uri, {
  headers: {
    Authorization: `Bearer ${await shopify.idToken()}`
  }
})