Going Further

Webhooks

Using Webhooks with Shopify in Nuxt

The Nuxt Shopify module provides functionality for managing webhook subscriptions and runtime request HMAC validation.

Configuration

To get started, you need to configure your webhooks under subscriptions in the nuxt.config.ts file. Shopify signs these webhooks with the client secret of your app. By default, the module uses the clientSecret of the admin client to validate them, or the secret option if you set it.

To subscribe / unsubscribe webhooks make sure you have also set up access to the Admin API in the module configuration.
export default defineNuxtConfig({
  modules: ['@nuxtjs/shopify'],

  shopify: {
    webhooks: {
      secret: '',

      subscriptions: [
        {
          topic: 'ORDERS_CREATE',
          uri: 'https://your-app.com/api/webhooks/orders-create',
        },
        {
          topic: 'PRODUCTS_UPDATE',
          uri: 'https://your-app.com/api/webhooks/products-update',
        }
      ],
    },
  },
})

Set the secret with the NUXT_SHOPIFY_WEBHOOKS_SECRET environment variable at runtime. If you read process.env in nuxt.config.ts instead, the secret is included in the build. Nuxt only uses the variable if the key exists at build time, so keep secret: '' as shown above, see environment variables.

.env
NUXT_SHOPIFY_WEBHOOKS_SECRET="..."

Options

OptionTypeDescription
secretstringThe secret for HMAC validation. Defaults to the admin client's clientSecret.
subscriptionsWebhook[]The webhook subscriptions to create.

Each entry in subscriptions can have the following properties:

  • topic (required): The topic of the webhook (e.g. ORDERS_CREATE).
  • uri (required): The URI where the webhook should be sent.
  • format (optional): The format of the webhook payload (JSON or XML). Defaults to JSON.
  • filter (optional): A filter for the webhook.
  • includeFields (optional): A list of fields to include in the webhook payload.
  • metafieldNamespaces (optional): A list of metafield namespaces to include.
  • metafields (optional): A list of metafields to include.

Managing Webhooks

The module provides a CLI command to easily manage your webhook subscriptions from your local development environment. It takes one of the actions list, subscribe or unsubscribe. With any other action, it exits with code 1, so a typo fails your CI job.

List Subscribed Webhooks

To list all currently subscribed webhooks for your shop:

npx @nuxtjs/shopify webhooks list

Subscribe to Webhooks

To subscribe to the webhooks configured in your nuxt.config.ts:

npx @nuxtjs/shopify webhooks subscribe

This command reads your configuration and creates a subscription for every webhook that is not subscribed yet.

A webhook is matched against Shopify by its topic and uri. When a match already exists, its format, filter, includeFields, metafieldNamespaces and metafields are compared against your configuration, and the subscription is updated if any of them differ. If everything matches, running the command again doesn't change anything.

If you change the topic or uri of a webhook, a new subscription is created and the old one is kept. To remove the old one, run webhooks unsubscribe with the previous configuration first, or remove it in your Shopify admin.

Unsubscribe from Webhooks

To unsubscribe from all webhooks configured in your nuxt.config.ts:

npx @nuxtjs/shopify webhooks unsubscribe

Handling Webhooks

To securely handle incoming webhooks, the module provides the defineWebhookEventHandler utility. This handler automatically validates the incoming request against your Shopify App Client Secret using HMAC validation.

Create a new server route (e.g. server/api/webhooks/orders-create.ts) and use defineWebhookEventHandler:

server/api/webhooks/orders-create.ts
export default defineWebhookEventHandler(async (event) => {
  const body = await readBody(event)

  const topic = getWebhookTopic(event)
  const shop = getWebhookShopDomain(event)

  console.log(`Received ${topic} webhook from ${shop}`)
  console.log('Payload:', body)

  // Handle the webhook payload
})

If the validation fails, the handler will automatically return a 401 Unauthorized response.

HMAC validation runs whenever webhooks.secret or the admin client's clientSecret is set, in development as well as in production. Only the case of a missing secret differs: nuxt dev accepts the request with a warning so local testing is possible, while a production build rejects it with a 401.

Helper Functions

The module provides several helper functions to extract information from the webhook request. These are available in your server routes:

  • getWebhookTopic(event): Returns the webhook topic.
  • getWebhookShopDomain(event): Returns the shop domain.
  • getWebhookHmac(event): Returns the HMAC signature.
  • getWebhookApiVersion(event): Returns the API version.
  • getWebhookId(event): Returns the webhook ID.
  • getWebhookTriggeredAt(event): Returns the timestamp when the webhook was triggered.
  • getWebhookEventId(event): Returns the event ID.

Validating Manually

If you cannot wrap your route in defineWebhookEventHandler, for example when the same route serves other traffic, or when you need to run logic before validation, call the auto-imported validateWebhook helper yourself. It performs the same HMAC check and throws a 401 Unauthorized error when the signature does not match:

server/api/webhooks/orders-create.ts
export default defineEventHandler(async (event) => {
  await validateWebhook(event)

  const body = await readBody(event)

  // Handle the webhook payload
})
validateWebhook reads the raw request body to compute the signature. Read the body afterwards, as shown above.
Published under the MIT License