Problem with afterAuth hook

Hi everyone,

I’m using remix template in my app and trying to automatically create a product when the app is installed using the afterAuth hook.

Here is my code:

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: ApiVersion.
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  restResources,
  future: {
    unstable_newEmbeddedAuthStrategy: true,
  },

  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
  hooks: {
    afterAuth: async ({ session, admin }) => {
      const response = await admin.graphql(
        `mutation {
                productCreate(input: {
                  title: "My test product",
                  productType: "Snowboard",
                  vendor: "JadedPixel"
                }) {
                  product {
                    id
                    title
                  }
                  userErrors {
                    field
                    message
                  }
                }
              }`,
      );
    },
  },
});

To trigger the afterAuth I uninstalled and in then installed the app again. However product was not created.

When I run the same GraphQL query using the Shopify CLI’s GraphiQL, the product is created.

Please, advice what I’m doing wrong?

@Ivan24 This could be related to sessions. afterAuth only runs when the auth flow runs, which will only happen if you do not have an active or valid session.

If you clear your app session storage and then try again, the afterAuth hook should run.

1 Like

@lukeclifton, many thanks for reply.

Am I right uninstalling the app from the dev store doesn’t clear the app session? Because, I tried to uninstall / install it but it did not help.

UPDATE: resolved by removing session records from the file prisma/dev.sqllite.

1 Like

@lvan24 To add to what @lukeclifton has answered, You might need to make sure if the app is not already installed (check if record exists) before doing any “One time” action using afterAuth

1 Like