--- title: Webhook description: Contains functions for verifying Shopify webhooks. api_version: v4 latest api_name: shopify-app-remix source_url: html: https://shopify.dev/docs/api/shopify-app-remix/latest/authenticate/webhook md: https://shopify.dev/docs/api/shopify-app-remix/latest/authenticate/webhook.md --- # Webhookobject Contains functions for verifying Shopify webhooks. ## authenticate.​webhook([request](#authenticatewebhook-propertydetail-request)​) Verifies requests coming from Shopify webhooks. ### Parameters * request Request required ### Returns * Promise\> ### WebhookContext ```ts WebhookContextWithoutSession | WebhookContextWithSession ``` ### WebhookContextWithoutSession * admin ```ts undefined ``` * apiVersion The API version used for the webhook. ```ts string ``` * payload The payload from the webhook request. ```ts Record ``` * session ```ts undefined ``` * shop The shop where the webhook was triggered. ```ts string ``` * subTopic The sub-topic of the webhook. This is only available for certain webhooks. ```ts string ``` * topic The topic of the webhook. ```ts Topics ``` * webhookId A unique ID for the webhook. Useful to keep track of which events your app has already processed. ```ts string ``` ```ts export interface WebhookContextWithoutSession extends Context { session: undefined; admin: undefined; } ``` ### WebhookContextWithSession * admin An admin context for the webhook. Returned only if there is a session for the shop. ```ts AdminApiContext ``` * apiVersion The API version used for the webhook. ```ts string ``` * payload The payload from the webhook request. ```ts Record ``` * session A session with an offline token for the shop. Returned only if there is a session for the shop. Webhook requests can trigger after an app is uninstalled If the app is already uninstalled, the session may be undefined. Therefore, you should check for the session before using it. ```ts Session ``` * shop The shop where the webhook was triggered. ```ts string ``` * subTopic The sub-topic of the webhook. This is only available for certain webhooks. ```ts string ``` * topic The topic of the webhook. ```ts Topics ``` * webhookId A unique ID for the webhook. Useful to keep track of which events your app has already processed. ```ts string ``` ````ts export interface WebhookContextWithSession extends Context { /** * A session with an offline token for the shop. * * Returned only if there is a session for the shop. * Webhook requests can trigger after an app is uninstalled * If the app is already uninstalled, the session may be undefined. * Therefore, you should check for the session before using it. * * @example * Protecting against uninstalled apps. * ```ts * // /app/routes/webhooks.tsx * import type { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "~/shopify.server"; * export const action = async ({ request }: ActionFunctionArgs) => { * const { session } = await authenticate.webhook(request); * * // Webhook requests can trigger after an app is uninstalled * // If the app is already uninstalled, the session may be undefined. * if (!session) { * throw new Response(); * } * * // Handle webhook request * console.log("Received webhook webhook"); * * return new Response(); * }; * ``` */ session: Session; /** * An admin context for the webhook. * * Returned only if there is a session for the shop. * * @example * Webhook admin context. * Use the `admin` object in the context to interact with the Admin API. * ```ts * // /app/routes/webhooks.tsx * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.webhook(request); * * // Webhook requests can trigger after an app is uninstalled * // If the app is already uninstalled, the session may be undefined. * if (!session) { * throw new Response(); * } * * const response = await admin?.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { variables: { input: { title: "Product Name" } } } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` */ admin: AdminApiContext; } ```` ### AdminApiContext * graphql Methods for interacting with the Shopify Admin GraphQL API ```ts GraphQLClient ``` ````ts export interface AdminApiContext { /** * Methods for interacting with the Shopify Admin GraphQL API * * {@link https://shopify.dev/docs/api/admin-graphql} * {@link https://github.com/Shopify/shopify-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } ```` ### GraphQLClient * query ```ts Operation extends keyof Operations ``` * options ```ts GraphQLQueryOptions ``` interface Promise\ { /\*\* \* Attaches callbacks for the resolution and/or rejection of the Promise. \* @param onfulfilled The callback to execute when the Promise is resolved. \* @param onrejected The callback to execute when the Promise is rejected. \* @returns A Promise for the completion of which ever callback is executed. \*/ then\(onfulfilled?: ((value: T) => TResult1 | PromiseLike\) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike\) | undefined | null): Promise\; /\*\* \* Attaches a callback for only the rejection of the Promise. \* @param onrejected The callback to execute when the Promise is rejected. \* @returns A Promise for the completion of the callback. \*/ catch\(onrejected?: ((reason: any) => TResult | PromiseLike\) | undefined | null): Promise\; }, interface Promise\ {}, Promise: PromiseConstructor, interface Promise\ { readonly \[Symbol.toStringTag]: string; }, interface Promise\ { /\*\* \* Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The \* resolved value cannot be modified from the callback. \* @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). \* @returns A Promise for the completion of the callback. \*/ finally(onfinally?: (() => void) | undefined | null): Promise\; } ```ts interface Promise { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; }, interface Promise {}, Promise: PromiseConstructor, interface Promise { readonly [Symbol.toStringTag]: string; }, interface Promise { /** * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The * resolved value cannot be modified from the callback. * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). * @returns A Promise for the completion of the callback. */ finally(onfinally?: (() => void) | undefined | null): Promise; } ``` ```ts < Operation extends keyof Operations, >( query: Operation, options?: GraphQLQueryOptions, ) => Promise> ``` ### GraphQLQueryOptions * apiVersion The version of the API to use for the request. ```ts ApiVersion ``` * headers Additional headers to include in the request. ```ts Record ``` * signal An optional AbortSignal to cancel the request. ```ts AbortSignal ``` * tries The total number of times to try the request if it fails. ```ts number ``` * variables The variables to pass to the operation. ```ts ApiClientRequestOptions["variables"] ``` ```ts export interface GraphQLQueryOptions< Operation extends keyof Operations, Operations extends AllOperations, > { /** * The variables to pass to the operation. */ variables?: ApiClientRequestOptions['variables']; /** * The version of the API to use for the request. */ apiVersion?: ApiVersion; /** * Additional headers to include in the request. */ headers?: Record; /** * The total number of times to try the request if it fails. */ tries?: number; /** * An optional AbortSignal to cancel the request. */ signal?: AbortSignal; } ``` ### Examples * #### Update a metafield when a product is updated ##### Description Update a metafield when a product is updated ##### /app/routes/\*\*.ts ```typescript import {type ActionFunctionArgs} from '@remix-run/node'; import {authenticate} from '../shopify.server'; export const action = async ({request}: ActionFunctionArgs) => { const {topic, admin, payload, session} = await authenticate.webhook(request); // Webhook requests can trigger after an app is uninstalled // If the app is already uninstalled, the session may be undefined. if (!session) { throw new Response(); } switch (topic) { case 'PRODUCTS_UPDATE': await admin.graphql( `#graphql mutation setMetafield($productId: ID!, $time: String!) { metafieldsSet(metafields: { ownerId: $productId namespace: "my-app", key: "webhook_received_at", value: $time, type: "string", }) { metafields { key value } } } `, { variables: { productId: payload.admin_graphql_api_id, time: new Date().toISOString(), }, }, ); } return new Response(); }; ``` ## Examples ### admin Webhook admin context Use the `admin` object in the context to interact with the Admin API. ### Examples * #### Webhook admin context ##### Description Use the \`admin\` object in the context to interact with the Admin API. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export async function action({ request }: ActionFunctionArgs) { const { admin } = await authenticate.webhook(request); // Webhook requests can trigger after an app is uninstalled // If the app is already uninstalled, the session may be undefined. if (!session) { throw new Response(); } const response = await admin?.graphql( `#graphql mutation populateProduct($input: ProductInput!) { productCreate(input: $input) { product { id } } }`, { variables: { input: { title: "Product Name" } } } ); const productData = await response.json(); return json({ data: productData.data }); } ``` ### apiVersion Webhook API version Get the API version used for webhook request. ### Examples * #### Webhook API version ##### Description Get the API version used for webhook request. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { apiVersion } = await authenticate.webhook(request); return new Response(); }; ``` ### payload Webhook payload Get the request's POST payload. ### Examples * #### Webhook payload ##### Description Get the request's POST payload. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { payload } = await authenticate.webhook(request); return new Response(); }; ``` ### session Protecting against uninstalled apps ### Examples * #### Protecting against uninstalled apps ##### /app/routes/webhooks.tsx ```typescript import type { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "~/shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { session } = await authenticate.webhook(request); // Webhook requests can trigger after an app is uninstalled // If the app is already uninstalled, the session may be undefined. if (!session) { throw new Response(); } // Handle webhook request console.log("Received webhook webhook"); return new Response(); }; ``` ### shop Webhook shop Get the shop that triggered a webhook. ### Examples * #### Webhook shop ##### Description Get the shop that triggered a webhook. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { shop } = await authenticate.webhook(request); return new Response(); }; ``` ### subTopic Webhook sub-topic Get the webhook sub-topic. ### Examples * #### Webhook sub-topic ##### Description Get the webhook sub-topic. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { subTopic } = await authenticate.webhook(request); return new Response(); }; ``` ### topic Webhook topic Get the event topic for the webhook. ### Examples * #### Webhook topic ##### Description Get the event topic for the webhook. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { topic } = await authenticate.webhook(request); switch (topic) { case "APP_UNINSTALLED": // Do something when the app is uninstalled. break; } return new Response(); }; ``` ### webhookId Webhook ID Get the webhook ID. ### Examples * #### Webhook ID ##### Description Get the webhook ID. ##### /app/routes/webhooks.tsx ```typescript import { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { webhookId } = await authenticate.webhook(request); return new Response(); }; ``` ## Related [Interact with the Admin API. - Admin API context](https://shopify.dev/docs/api/shopify-app-remix/apis/admin-api)