401 Error When Retrieving Token After Login - Need Help With Origin error

I’ve been facing a persistent issue while developing my app integration with Shopify. I’m trying to use the new Clients Api with my headless store (Nextjs). I consistently receive a 401 error when I try to retrieve the token post-login. I’ve been working on ensuring that the origin header is correctly set, as the documentation suggested that a 401 with the message invalid_token might be related to the origin header.

Here’s a brief code snippet to give you an idea:

const headers = {
  'content-type': 'application/x-www-form-urlencoded',
  'User-Agent': userAgent,
  'Origin': new URL(request.url).origin.replace('http', 'https')
};

const response = await fetch(`${customerAccountUrl}/auth/oauth/token`, {
  method: 'POST',
  headers,
  body
});

I’ve even tried using ngrok to expose my localhost for development purposes and attempted to whitelist the ngrok domain in my Shopify settings. However, I learned that Shopify needs to verify the domain through a CNAME record, which isn’t feasible with a temporary ngrok domain.

I’m at a bit of a loss and would appreciate any insights or suggestions you might have. Has anyone else encountered this issue, and if so, how did you resolve it?

Thank you in advance for your help!