Add Product Metafield definitions programatically on app installation

I’m working on a shopify app build with remix in typescript.

I want to add a product metafield upon app installation. I’ve tried a few approaches and didn’t get anywhere. I tried using a webhook, but there is no webhook topic for app installation according to https://shopify.dev/docs/api/webhooks?reference=toml#list-of-topics
I tried adding custom code using the afterAuth hook method but I cannot get this working, it seems that the afterAuth method is just never called as none of the logs are being called there. The session is created and stored in my DB when I install the app. The Product metafield definitions in my shopify dev store remain empty
Here’s the relevant code snippet to create the metafield definition:

const createMetafieldDefinition = await client.query({ data: { query: mutation CreateMetafieldDefinition($definition: MetafieldDefinitionInput!) { metafieldDefinitionCreate(definition: $definition) { createdDefinition { id name } userErrors { field message code } } }, variables: { definition: { name: “My App”, namespace: “my_app_namespace”, key: “my_metafield_key”, description: “Field created by my app”, type: “single_line_text_field”, ownerType: “PRODUCT” } } } });

Can anyone point me into the right direction to get this working?

Hello,

You need to do certain changes on shopify.server.ts file. Here you will find app auth installation hook.

hooks: {
afterAuth: async ({ session, admin }) => {
shopify.registerWebhooks({ session });
console.log("------------------------afterAuth--------------------------");
},
},}

Here you can write createMetafieldDefinition upon app installation.

1 Like

Thank you, the issue was that I added the afterAuth method at root level of the shopifyApp constructor rather than within the hooks field