Shopify / hydrogen

Hydrogen lets you build faster headless storefronts in less time, on Shopify.
https://hydrogen.shop
MIT License
1.35k stars 261 forks source link

"Bad request: Unauthorized" for Customer Account API Login for Shopify Hydrogen Development (Hosted through Ngrok) #2399

Closed cc-visionary closed 1 month ago

cc-visionary commented 1 month ago

What is the location of your example repository?

No response

Which package or tool is having this issue?

Hydrogen

What version of that package or tool are you using?

2024.7.2

What version of Remix are you using?

2.10.1

Steps to Reproduce

I used the shopify hydrogen skeleton template.

Then followed the documentation: https://shopify.dev/docs/storefronts/headless/building-with-the-customer-account-api/hydrogen where:

  1. Setup NGROK the Environment image
  2. Create the Customer Account API client (didn't modify anything in the sever.js file of the template)

    const waitUntil = executionContext.waitUntil.bind(executionContext);
    const [cache, session] = await Promise.all([
    caches.open('hydrogen'),
    AppSession.init(request, [env.SESSION_SECRET]),
    ]);
    
    /**
    * Create Hydrogen's Storefront client.
    */
    const {storefront} = createStorefrontClient({
    cache,
    waitUntil,
    i18n: getLocaleFromRequest(request),
    publicStorefrontToken: env.PUBLIC_STOREFRONT_API_TOKEN,
    privateStorefrontToken: env.PRIVATE_STOREFRONT_API_TOKEN,
    storeDomain: env.PUBLIC_STORE_DOMAIN,
    storefrontId: env.PUBLIC_STOREFRONT_ID,
    storefrontHeaders: getStorefrontHeaders(request),
    });
    
    /**
    * Create a client for Customer Account API.
    */
    const customerAccount = createCustomerAccountClient({
    waitUntil,
    request,
    session,
    customerAccountId: env.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID,
    customerAccountUrl: env.PUBLIC_CUSTOMER_ACCOUNT_API_URL,
    });

I also did npx shopify hydrogen env pull to sync the environment variables.

I have also tried npx shopify hydrogen dev --customer-account-push__unstable which I saw in a discussion, but the result is the same.

Expected Behavior

The expected behavior is that I am supposed to be logged in already.

Actual Behavior

But the website returns Bad request: Unauthorized and the console says Customer Account API Error: The session state does not match the state parameter. Make sure that the session is configured correctly and passed to 'createCustomerAccountClient'. image

jnhamid commented 1 month ago

@cc-visionary I had this error too after I upgraded from 2024.4.x to 2024.7.2.

Also make sure you add 'wss://ngrok-domain.app:*' (replace with your ngrok domain) to your connect-src in your createContentSecurityPolicy function call

Doing this step in the upgrade manual seemed to help the issue

[Breaking Change] New session commit pattern #2137

Step: 1. Add isPending implementation in session #2137

#2137

// in app/lib/session.ts
export class AppSession implements HydrogenSession {
+  public isPending = false;

  get unset() {
+    this.isPending = true;
    return this.#session.unset;
  }

  get set() {
+    this.isPending = true;
    return this.#session.set;
  }

  commit() {
+    this.isPending = false;
    return this.#sessionStorage.commitSession(this.#session);
  }
}

Step: 2. update response header if session.isPending is true #2137

#2137

// in server.ts
export default {
  async fetch(request: Request): Promise<Response> {
    try {
      const response = await handleRequest(request);

+      if (session.isPending) {
+        response.headers.set('Set-Cookie', await session.commit());
+      }

      return response;
    } catch (error) {
      ...
    }
  },
};

Step: 3. remove setting cookie with session.commit() in routes #2137

#2137

// in route files
export async function loader({context}: LoaderFunctionArgs) {
  return json({},
-    {
-      headers: {
-        'Set-Cookie': await context.session.commit(),
-      },
    },
  );
}
blittle commented 1 month ago

Thank you @jnhamid

cc-visionary commented 1 month ago

Thank you so much! It's working now!

dgamma3 commented 1 week ago

also worked for me, thanks so much bro, didn't need step 3. I'm on 2024.7.5