Webhookobject
Contains functions for verifying Shopify webhooks.
Verifies requests coming from Shopify webhooks.
- Anchor to requestrequestRequestrequired
AuthenticateWebhook
- request
Request
Promise<WebhookContext<Topics>>
(
request: Request,
) => Promise<WebhookContext<Topics>>
WebhookContext
WebhookContextWithoutSession<Topics> | WebhookContextWithSession<Topics>
WebhookContextWithoutSession
- admin
undefined
- apiVersion
The API version used for the webhook.
string
- payload
The payload from the webhook request.
Record<string, any>
- session
undefined
- shop
The shop where the webhook was triggered.
string
- subTopic
The sub-topic of the webhook. This is only available for certain webhooks.
string
- topic
The topic of the webhook.
Topics
- webhookId
A unique ID for the webhook. Useful to keep track of which events your app has already processed.
string
export interface WebhookContextWithoutSession<Topics = string | number | symbol>
extends Context<Topics> {
session: undefined;
admin: undefined;
}
WebhookContextWithSession
- admin
An admin context for the webhook. Returned only if there is a session for the shop.
AdminApiContext
- apiVersion
The API version used for the webhook.
string
- payload
The payload from the webhook request.
Record<string, any>
- 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.
Session
- shop
The shop where the webhook was triggered.
string
- subTopic
The sub-topic of the webhook. This is only available for certain webhooks.
string
- topic
The topic of the webhook.
Topics
- webhookId
A unique ID for the webhook. Useful to keep track of which events your app has already processed.
string
export interface WebhookContextWithSession<Topics = string | number | symbol>
extends Context<Topics> {
/**
* 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
* <caption>Protecting against uninstalled apps.</caption>
* ```ts
* // /app/routes/webhooks.tsx
* import type { ActionFunctionArgs } from "react-router";
* 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
* <caption>Webhook admin context.</caption>
* <description>Use the `admin` object in the context to interact with the Admin API.</description>
* ```ts
* // /app/routes/webhooks.tsx
* import { ActionFunctionArgs } from "react-router";
* 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 ({ data: productData.data });
* }
* ```
*/
admin: AdminApiContext;
}
AdminApiContext
- graphql
Methods for interacting with the Shopify Admin GraphQL API
GraphQLClient<AdminOperations>
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
* <caption>Querying the GraphQL API.</caption>
* <description>Use `admin.graphql` to make query / mutation requests.</description>
* ```ts
* // /app/routes/**\/*.ts
* import { ActionFunctionArgs } from "react-router";
* 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 ({
* productId: productData.data?.productCreate?.product?.id,
* });
* }
* ```
*
* ```ts
* // /app/shopify.server.ts
* import { shopifyApp } from "@shopify/shopify-app-react-router/server";
*
* const shopify = shopifyApp({
* // ...
* });
* export default shopify;
* export const authenticate = shopify.authenticate;
* ```
*
* @example
* <caption>Handling GraphQL errors.</caption>
* <description>Catch `GraphqlQueryError` errors to see error messages from the API.</description>
* ```ts
* // /app/routes/**\/*.ts
* import { ActionFunctionArgs } from "react-router";
* 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 ({ 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 ({ errors: error.body?.errors }, { status: 500 });
* }
* return ({ message: "An error occurred" }, { status: 500 });
* }
* }
* ```
*
* ```ts
* // /app/shopify.server.ts
* import { shopifyApp } from "@shopify/shopify-app-react-router/server";
*
* const shopify = shopifyApp({
* // ...
* });
* export default shopify;
* export const authenticate = shopify.authenticate;
* ```
*/
graphql: GraphQLClient<AdminOperations>;
}
GraphQLClient
- query
Operation extends keyof Operations
- options
GraphQLQueryOptions<Operation, Operations>
interface Promise<T> {
/**
* 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<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* 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<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}, interface Promise<T> {}, Promise: PromiseConstructor, interface Promise<T> {
readonly [Symbol.toStringTag]: string;
}, interface Promise<T> {
/**
* 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<T>;
}
<
Operation extends keyof Operations,
>(
query: Operation,
options?: GraphQLQueryOptions<Operation, Operations>,
) => Promise<GraphQLResponse<Operation, Operations>>
GraphQLQueryOptions
- apiVersion
The version of the API to use for the request.
ApiVersion
- headers
Additional headers to include in the request.
Record<string, any>
- signal
An optional AbortSignal to cancel the request.
AbortSignal
- tries
The total number of times to try the request if it fails.
number
- variables
The variables to pass to the operation.
ApiClientRequestOptions<Operation, Operations>["variables"]
export interface GraphQLQueryOptions<
Operation extends keyof Operations,
Operations extends AllOperations,
> {
/**
* The variables to pass to the operation.
*/
variables?: ApiClientRequestOptions<Operation, Operations>['variables'];
/**
* The version of the API to use for the request.
*/
apiVersion?: ApiVersion;
/**
* Additional headers to include in the request.
*/
headers?: Record<string, any>;
/**
* The total number of times to try the request if it fails.
*/
tries?: number;
/**
* An optional AbortSignal to cancel the request.
*/
signal?: AbortSignal;
}
Update a metafield when a product is updated
/app/routes/**.ts
examples
Update a metafield when a product is updated
description
Update a metafield when a product is updated
/app/routes/**.ts
import {type ActionFunctionArgs} from 'react-router'; 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(); };
Anchor to examplesExamples
Anchor to example-webhook-admin-contextWebhook admin context
Use the admin
object in the context to interact with the Admin API.
Webhook admin context
/app/routes/webhooks.tsx
examples
Webhook admin context
description
Use the `admin` object in the context to interact with the Admin API.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; 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 ({ data: productData.data }); }
Anchor to example-apiversionapiVersion
Anchor to example-webhook-api-versionWebhook API version
Get the API version used for webhook request.
Webhook API version
/app/routes/webhooks.tsx
examples
Webhook API version
description
Get the API version used for webhook request.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { apiVersion } = await authenticate.webhook(request); return new Response(); };
Anchor to example-payloadpayload
Anchor to example-webhook-payloadWebhook payload
Get the request's POST payload.
Webhook payload
/app/routes/webhooks.tsx
examples
Webhook payload
description
Get the request's POST payload.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { payload } = await authenticate.webhook(request); return new Response(); };
Anchor to example-sessionsession
Anchor to example-protecting-against-uninstalled-appsProtecting against uninstalled apps
Protecting against uninstalled apps
/app/routes/webhooks.tsx
examples
Protecting against uninstalled apps
/app/routes/webhooks.tsx
import type { ActionFunctionArgs } from "react-router"; 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(); };
Anchor to example-webhook-shopWebhook shop
Get the shop that triggered a webhook.
Webhook shop
/app/routes/webhooks.tsx
examples
Webhook shop
description
Get the shop that triggered a webhook.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { shop } = await authenticate.webhook(request); return new Response(); };
Anchor to example-subtopicsubTopic
Anchor to example-webhook-sub-topicWebhook sub-topic
Get the webhook sub-topic.
Webhook sub-topic
/app/routes/webhooks.tsx
examples
Webhook sub-topic
description
Get the webhook sub-topic.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { subTopic } = await authenticate.webhook(request); return new Response(); };
Anchor to example-webhook-topicWebhook topic
Get the event topic for the webhook.
Webhook topic
/app/routes/webhooks.tsx
examples
Webhook topic
description
Get the event topic for the webhook.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; 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(); };
Anchor to example-webhookidwebhookId
Anchor to example-webhook-idWebhook ID
Get the webhook ID.
Webhook ID
/app/routes/webhooks.tsx
examples
Webhook ID
description
Get the webhook ID.
/app/routes/webhooks.tsx
import { ActionFunctionArgs } from "react-router"; import { authenticate } from "../shopify.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { webhookId } = await authenticate.webhook(request); return new Response(); };