Issue calling shopify app api from checkout UI extension

Issue calling shopify app api from checkout UI extension

HridayHegde
Shopify Partner
1 0 0

Hi,
I am building a shopify custom app with a checkout UI extension. I have used the cli to get started with the remix template. The checkout UI extension itself is working fine, but now I want to make a call to the admin to retrieve some data, i built an api for this under
app > api.updatesavedcartdata.jsx (ignore the naming)

import { json } from "@remix-run/node";
export async function loader({ request }) {
  return json(
    { data: "HELLO" }
  );
}


Now i am trying to call this api in my checkoutUI extension 

 
const response = await fetch(
      `https://wise-casey-windows-novel.trycloudflare.com/api/updatesavedcartdata`
    );
    console.log("helo", response);
 

Where https://wise-casey-windows-novel.trycloudflare.com is the cloudflare link it generates on using `yarn run dev`. When I do this I get a cors origin error on the checkout page where the checkout ui loads the error:

Access to fetch at 'https://wise-casey-windows-novel.trycloudflare.com/api/updatesavedcartdata' from origin 'https://cdn.shopify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

 I tried changing and adding cors headers to the api response

export async function loader({ request }: ActionFunctionArgs) {
  return json(
    { data: "HELLO" },
    {
      headers: {
        "Access-Control-Allow-Origin": "https://cdn.shopify.com",
      },
    }
  );
}


But this just removed the error and now sends back the response

Response {type: 'cors', url: 'https://wise-casey-windows-novel.trycloudflare.com/api/updatesavedcartdata', redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: ""type: "cors"url: "https://wise-casey-windows-novel.trycloudflare.com/api/updatesavedcartdata"[[Prototype]]: Response


The correct response should be

{"data":"HELLO"}


I have all the permissions set that i would need to do this including network access. And hitting the link in the browser works normally

Any help would be appreciated on implementing this. My final use case is reading the customer's tags or metafields to set a condition. If there are any alternative approaches to this that would be fine as well  (currently by calling the admin graphql with customerid in the api)

Thanks,
Hriday


 

 

Replies 13 (13)

Liam
Shopify Staff
2807 310 805

Hi HridayHegde,

 

It looks like you're encountering CORS issues due to the different origins of your Shopify app and your API. The error message suggests that the Access-Control-Allow-Origin header is not present in the response from your API.

You might have tried to set this header in your API response, but as the error still persists, you can try the following solutions:

  1. Set the Access-Control-Allow-Origin header to *: This will allow requests from any origin. If your API doesn't contain sensitive information and it's okay to be accessed from anywhere, you can try this approach.
export async function loader({ request }: ActionFunctionArgs) {
  return json(
    { data: "HELLO" },
    {
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
    }
  );
}
  1. Include additional CORS headers: Sometimes, you need to include more headers to pass the CORS policy, like Access-Control-Allow-Methods and Access-Control-Allow-Headers.
export async function loader({ request }: ActionFunctionArgs) {
  return json(
    { data: "HELLO" },
    {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods "GET, POST, PUT, DELETE",
        "Access-Control-Allow-Headers": "Content-Type"
      },
    }
  );
}
  1. Use a CORS middleware: If you're using express.js or similar, you could use a CORS middleware to handle CORS in your API.
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
  1. Use a proxy Another option would be to use a proxy server to bypass CORS. This is often used for development and might not be the best option for production.

Hope this helps!

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

jains
Shopify Partner
11 0 4

Hi Liam

How do we digest the session token in the backend route so that we can then make calls to to Shopify API etc?

function Extension() {
const translate = useTranslate();
const { extension } = useApi();
const session = useSessionToken();

useEffect(() => {
const getTokenAndSendRequest = async () => {
const token = await session.get();
await sendRequest(token);
};

const sendRequest = async (token) => {
console.log(token);
headers: {
'Authorization': `Bearer ${token}`,
},
});

// Process response as needed
const data = await response.json();
console.log('Response:', data);
};

getTokenAndSendRequest();
}, [session, translate, extension]);

return (
<Banner title="gwp-discount-code">
{translate('welcome', { target: extension.target })}
</Banner>
);
}

muhammadluqman1
Shopify Partner
3 0 2

Same problem- Did you find any solution?

Liam
Shopify Staff
2807 310 805

Hi Muhammadluqman1,

 

Did you try the troubleshooting steps listed above? 

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

muhammadluqman1
Shopify Partner
3 0 2

I did, same error::
Access to fetch at 'https://julian-jury-blame-rental.trycloudflare.com/api/postTransaction' from origin 'https://cdn.shopify.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resour

Faisal235711
Shopify Partner
2 0 2

Hello. Did you manage to solve this issue? I'm also facing the same.

Brain Station 23
Darshanmandasa
Shopify Partner
3 0 2

I am also doing the same thing as you have done, I have solved all the errors but when I send the request, I am getting status code 302 or I am being redirected to the store login page, but I am not understanding it. What is he doing?

Please see the screenshot below  i have sent request sss (ignore naming) but  it gives me 302 and redirect to login page you can also see that thing

Darshanmandasa
Shopify Partner
3 0 2

Screenshot 2024-02-08 115021.png

StevenFitzAA
Shopify Partner
15 0 5

Facing the same issue, is there any examples out there of a Checkout UI extension able to call resource route of your remix app?

Be it proxy or call directly?

NehaD
Shopify Partner
1 0 1

Did you find any solution to Checkout UI extension able to call resource route of your remix app, if yes can you provide example here

bootsgridDev
Shopify Partner
17 0 0

Facing exactly  Same issue. Have you found any solution for this 302 response & redirecting to password page

Robles
Tourist
4 0 3

Same issue... and without solution for the moment.

 

jains
Shopify Partner
11 0 4

Also having this issue