CORS error when accessing Customer Account API token endpoint with public client type.

lizn
Shopify Partner
4 0 1

Hi there, I'm using the customer accounts api to authenticate my b2b users from my next js headless storefront hosted on netlify.

 

My client type is set to public and I am able to successfully retrieve a code from https://shopify.com/<store  id>/auth/oauth/authorize and set the code verifier. 

The problem is the second step in the authentication process, the call to
shopify.com/< my store id >/auth/oauth/token is returning 401 unauthorized with a cors error.

 

I have tried both the https netlify.live domain generated by the netlify cli, as well as an ngrok tunnel, with the respective origins and endpoints set in my application settings, but the result is the same. 

 

Here is my function:

 

export async function codeToToken(router) {
  const code = router.query.code;

  const clientId = process.env.NEXT_PUBLIC_SHOPIFY_NEW_CUSTOMER_CLIENT_ID;

  const body = new URLSearchParams();
  body.append("grant_type", "authorization_code");
  body.append("client_id", clientId);
  body.append(
    "redirect_uri",
    `https://<my live link domain>.netlify.live/account/`
  );
  body.append("code", code);

  // Public Client
  const codeVerifier = localStorage.getItem("code-verifier");
  body.append("code_verifier", codeVerifier);

  const headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    Origin: "https://<my live link domain>.netlify.live",
  };

  const tokenRequestUrl = "https://shopify.com/<my store id>/auth/oauth/token";

  const response = await fetch(tokenRequestUrl, {
    method: "POST",
    headers: headers,
    body: body,
  });

  if (!response.ok) {
    throw new Response(await response.text(), {
      status: response.status,
      headers: {
        "Content-Type": "text/html; charset=utf-8",
      },
    });
  }
  const { access_token, expires_in, id_token, refresh_token } =
    await response.json();

}

 


Thanks in advance. 

Replies 2 (2)

ErSanjay
Shopify Partner
307 20 44

@lizn  I can do the troubleshoot this issue.

Business Owner & Shopify Plus, Shopify app , Shopify Consultant - Full Stack Sofware Engineer
Warm regards,
Er Sanjay

If you find yourself in need of assistance with your store, don't hesitate to reach out! Feel free to send me a direct message, and I'll do my best to help you out.
lizn
Shopify Partner
4 0 1

Hi @ErSanjay  
If you can help me reach a solution that would be great. I'm attaching a screenshot of my console errors. As you can see I am getting the CORS error as described above. It's as if entering my endpoints for authorization in the headless app settings has no effect. What do you recommend I try next?

Screenshot 2024-05-07 at 4.28.46 PM.png