--- title: shopifyApp description: |- Returns a set of functions that can be used by the app's backend to be able to respond to all Shopify requests. The shape of the returned object changes depending on the value of `distribution`. If it is `AppDistribution.ShopifyAdmin`, then only `ShopifyAppBase` objects are returned, otherwise `ShopifyAppLogin` objects are included. api_version: v4 latest api_name: shopify-app-remix source_url: html: https://shopify.dev/docs/api/shopify-app-remix/latest/entrypoints/shopifyapp md: https://shopify.dev/docs/api/shopify-app-remix/latest/entrypoints/shopifyapp.md --- # shopify​Appfunction Returns a set of functions that can be used by the app's backend to be able to respond to all Shopify requests. The shape of the returned object changes depending on the value of `distribution`. If it is `AppDistribution.ShopifyAdmin`, then only `ShopifyAppBase` objects are returned, otherwise `ShopifyAppLogin` objects are included. ## shopify​App([appConfig](#shopifyapp-propertydetail-appconfig)​) Function to create a new Shopify API object. ### Parameters * appConfig Readonly\ required Configuration options for your Shopify app, such as the scopes your app needs. ### Returns * ShopifyApp\> `ShopifyApp` An object constructed using your appConfig. It has methods for interacting with Shopify. ### Readonly * readonly ```ts true ``` ```ts interface Readonly { readonly?: true; } ``` ### ShopifyApp An object your app can use to interact with Shopify. By default, the app's distribution is \`AppStore\`. ```ts Config['distribution'] extends AppDistribution.ShopifyAdmin ? AdminApp : Config['distribution'] extends AppDistribution.SingleMerchant ? EnforceSessionStorage> : Config['distribution'] extends AppDistribution.AppStore ? EnforceSessionStorage> : EnforceSessionStorage> ``` ### AppDistribution * AppStore ```ts app_store ``` * SingleMerchant ```ts single_merchant ``` * ShopifyAdmin ```ts shopify_admin ``` ```ts export enum AppDistribution { AppStore = 'app_store', SingleMerchant = 'single_merchant', ShopifyAdmin = 'shopify_admin', } ``` ### AdminApp * addDocumentResponseHeaders Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ```ts AddDocumentResponseHeaders ``` * authenticate Ways to authenticate requests from different surfaces across Shopify. ```ts Authenticate ``` * registerWebhooks Register shop-specific webhook subscriptions using the Admin GraphQL API. In many cases defining app-specific webhooks in the \`shopify.app.toml\` will be sufficient and easier to manage. Please see: You should only use this if you need shop-specific webhooks. ```ts RegisterWebhooks ``` * sessionStorage The \`SessionStorage\` instance you passed in as a config option. ```ts SessionStorageType ``` * unauthenticated Ways to get Contexts from requests that do not originate from Shopify. ```ts Unauthenticated ``` ```ts ShopifyAppBase ``` ### AddDocumentResponseHeaders * request ```ts Request ``` * headers ```ts Headers ``` void ```ts void ``` ```ts (request: Request, headers: Headers) => void ``` ### Authenticate * admin Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. Examples of when to use this are requests from your app's UI, or requests from admin extensions. If there is no session for the Request, this will redirect the merchant to correct auth flows. ```ts AuthenticateAdmin ``` * flow Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access the API, and the payload of the request. If there is no session for the Request, this will return an HTTP 400 error. Note that this will always be a POST request. ```ts AuthenticateFlow ``` * fulfillmentService Authenticate a request from a fulfillment service and get back an authenticated context. ```ts AuthenticateFulfillmentService ``` * public Authenticate a public request and get back a session token. ```ts AuthenticatePublic ``` * webhook Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request ```ts AuthenticateWebhook ``` ````ts interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * const response = await admin.graphql(`{ shop { name } }`) * * return json(await response.json()); * } * ``` * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ admin: AuthenticateAdmin; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ flow: AuthenticateFlow; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin, session } = await authenticate.fulfillmentService(request); * * console.log(session.id) * * return new Response(); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // app/routes/webhooks.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session, payload } = 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 the webhook * console.log(`${TOPIC} webhook received with payload:`, JSON.stringify(payload)) * * throw new Response(); * }; * ``` * * @example * Registering app-specific webhooks (Recommended) * ```toml * # shopify.app.toml * [webhooks] * api_version = "2024-07" * [[webhooks.subscriptions]] * topics = ["products/create"] * uri = "/webhooks/products/create" * * ``` * * @example * Registering shop-specific webhooks. * In many cases you won't need this. Please see: [https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-vs-shop-specific-subscriptions](https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-vs-shop-specific-subscriptions) * * ```ts * // app/shopify.server.ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * webhooks: { * PRODUCTS_CREATE: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks/products/create", * }, * }, * hooks: { * afterAuth: async ({ session }) => { * // Register webhooks for the shop * // In this example, every shop will have these webhooks * // You could wrap this in some custom shop specific conditional logic if needed * shopify.registerWebhooks({ session }); * }, * }, * // ...etc * }); * ``` */ webhook: AuthenticateWebhook; } ```` ### AuthenticateAdmin * request ```ts Request ``` Promise\> ```ts Promise> ``` ```ts ( request: Request, ) => Promise> ``` ### AdminContext ```ts EmbeddedTypedAdminContext & ScopesContext ``` ### EmbeddedTypedAdminContext ```ts Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext : EmbeddedAdminContext ``` ### NonEmbeddedAdminContext * admin Methods for interacting with the GraphQL Admin API for the store that made the request. ```ts AdminApiContext ``` * billing Billing methods for this store, based on the plans defined in the \`billing\` config option. ```ts BillingContext ``` * cors A function that ensures the CORS headers are set correctly for the response. ```ts EnsureCORSFunction ``` * session The session for the user who made the request. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. Use this to get shop or user-specific data. ```ts Session ``` ```ts export interface NonEmbeddedAdminContext extends AdminContextInternal {} ``` ### 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; } ``` ### ApiVersion * October22 ```ts 2022-10 ``` * January23 ```ts 2023-01 ``` * April23 ```ts 2023-04 ``` * July23 ```ts 2023-07 ``` * October23 ```ts 2023-10 ``` * January24 ```ts 2024-01 ``` * April24 ```ts 2024-04 ``` * July24 ```ts 2024-07 ``` * October24 ```ts 2024-10 ``` * January25 ```ts 2025-01 ``` * April25 ```ts 2025-04 ``` * July25 ```ts 2025-07 ``` * October25 ```ts 2025-10 ``` * Unstable ```ts unstable ``` ```ts export declare enum ApiVersion { October22 = "2022-10", January23 = "2023-01", April23 = "2023-04", July23 = "2023-07", October23 = "2023-10", January24 = "2024-01", April24 = "2024-04", July24 = "2024-07", October24 = "2024-10", January25 = "2025-01", April25 = "2025-04", July25 = "2025-07", October25 = "2025-10", Unstable = "unstable" } ``` ### BillingContext * cancel Cancels an ongoing subscription, given its ID. ```ts (options: CancelBillingOptions) => Promise ``` * check Checks if the shop has an active payment for any plan defined in the \`billing\` config option. ```ts >(options?: Options) => Promise ``` * createUsageRecord Creates a usage record for an app subscription. ```ts (options: CreateUsageRecordOptions) => Promise ``` * request Requests payment for the plan. ```ts (options: RequestBillingOptions) => Promise ``` * require Checks if the shop has an active payment for any plan defined in the \`billing\` config option. ```ts (options: RequireBillingOptions) => Promise ``` * updateUsageCappedAmount Updates the capped amount for a usage billing plan. ```ts (options: UpdateUsageCappedAmountOptions) => Promise ``` ````ts export interface BillingContext { /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Requesting billing right away. * Call `billing.request` in the `onFailure` callback to immediately redirect to the Shopify page to request payment. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * isTest: true, * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Redirect to a plan selection page. * When the app has multiple plans, create a page in your App that allows the merchant to select a plan. If a merchant does not have the required plan you can redirect them to page in your app to select one. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, redirect } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN, ANNUAL_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN, ANNUAL_PLAN], * isTest: true, * onFailure: () => redirect('/select-plan'), * }); * * const subscription = billingCheck.appSubscriptions[0]; * console.log(`Shop is on ${subscription.name} (id ${subscription.id})`); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * [ANNUAL_PLAN]: { * lineItems: [ * { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ require: ( options: RequireBillingOptions, ) => Promise; /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Check what billing plans a merchant is subscribed to. * Use billing.check if you want to determine which plans are in use. Unlike `require`, `check` does not * throw an error if no active billing plans are present. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const { hasActivePayment, appSubscriptions } = await billing.check({ * plans: [MONTHLY_PLAN], * isTest: false, * }); * console.log(hasActivePayment); * console.log(appSubscriptions); * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * [ANNUAL_PLAN]: { * lineItems: [ * { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Check for payments without filtering. * Use billing.check to see if any payments exist for the store, regardless of whether it's a test or * matches one or more plans. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const { hasActivePayment, appSubscriptions } = await billing.check(); * // This will be true if any payment is found * console.log(hasActivePayment); * console.log(appSubscriptions); * }; * ``` */ check: >( options?: Options, ) => Promise; /** * Requests payment for the plan. * * @returns Redirects to the confirmation URL for the payment. * * @example * Using a custom return URL. * Change where the merchant is returned to after approving the purchase using the `returnUrl` option. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ * plan: MONTHLY_PLAN, * isTest: true, * returnUrl: 'https://admin.shopify.com/store/my-store/apps/my-app/billing-page', * }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * [ANNUAL_PLAN]: { * lineItems: [ * { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Overriding plan settings. * Customize the plan for a merchant when requesting billing. Any fields from the plan can be overridden, as long as the billing interval for line items matches the config. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ * plan: MONTHLY_PLAN, * isTest: true, * trialDays: 14, * lineItems: [ * { * interval: BillingInterval.Every30Days, * discount: { value: { percentage: 0.1 } }, * }, * ], * }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * [ANNUAL_PLAN]: { * lineItems: [ * { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ request: (options: RequestBillingOptions) => Promise; /** * Cancels an ongoing subscription, given its ID. * * @returns The cancelled subscription. * * @example * Cancelling a subscription. * Use the `billing.cancel` function to cancel an active subscription with the id returned from `billing.require`. * ```ts * // /app/routes/cancel-subscription.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * const subscription = billingCheck.appSubscriptions[0]; * const cancelledSubscription = await billing.cancel({ * subscriptionId: subscription.id, * isTest: true, * prorate: true, * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * } * ], * }, * [ANNUAL_PLAN]: { * lineItems: [ * { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ cancel: (options: CancelBillingOptions) => Promise; /** * Creates a usage record for an app subscription. * * @returns Returns a usage record when one was created successfully. * * @example * Creating a usage record * Create a usage record for the active usage billing plan * ```ts * // /app/routes/create-usage-record.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { billing } = await authenticate.admin(request); * * const chargeBilling = await billing.createUsageRecord({ * description: "Usage record for product creation", * price: { * amount: 1, * currencyCode: "USD", * }, * isTest: true, * }); * console.log(chargeBilling); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const USAGE_PLAN = 'Usage subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [USAGE_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Usage, * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ createUsageRecord: ( options: CreateUsageRecordOptions, ) => Promise; /** * Updates the capped amount for a usage billing plan. * * @returns Redirects to a confirmation page to update the usage billing plan. * * @example * Updating the capped amount for a usage billing plan. * Update the capped amount for the usage billing plan specified by `subscriptionLineItemId`. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { billing } = await authenticate.admin(request); * * await billing.updateUsageCappedAmount({ * subscriptionLineItemId: "gid://shopify/AppSubscriptionLineItem/12345?v=1&index=1", * cappedAmount: { * amount: 10, * currencyCode: "USD" * }, * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const USAGE_PLAN = 'Usage subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [USAGE_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Usage, * terms: "Usage based" * } * ], * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ updateUsageCappedAmount: ( options: UpdateUsageCappedAmountOptions, ) => Promise; } ```` ### CancelBillingOptions * isTest Whether to use the test mode. This prevents the credit card from being charged. ```ts boolean ``` * prorate Whether to issue prorated credits for the unused portion of the app subscription. There will be a corresponding deduction (based on revenue share) to your Partner account. For example, if a $10.00 app subscription (with 0% revenue share) is cancelled and prorated half way through the billing cycle, then the merchant will be credited $5.00 and that amount will be deducted from your Partner account. ```ts boolean ``` * subscriptionId The ID of the subscription to cancel. ```ts string ``` ```ts export interface CancelBillingOptions { /** * The ID of the subscription to cancel. */ subscriptionId: string; /** * Whether to issue prorated credits for the unused portion of the app subscription. There will be a corresponding * deduction (based on revenue share) to your Partner account. For example, if a $10.00 app subscription * (with 0% revenue share) is cancelled and prorated half way through the billing cycle, then the merchant will be * credited $5.00 and that amount will be deducted from your Partner account. */ prorate?: boolean; /** * Whether to use the test mode. This prevents the credit card from being charged. */ isTest?: boolean; } ``` ### Options * layout Whether to use the shop's theme layout around the Liquid content. ```ts boolean ``` ```ts interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } ``` ### CheckBillingOptions * isTest Whether to include charges that were created on test mode. Test shops and demo shops cannot be charged. ```ts boolean ``` * plans The plans to check for. Must be one of the values defined in the \`billing\` config option. ```ts (keyof Config["billing"])[] ``` ```ts export interface CheckBillingOptions extends Omit { /** * The plans to check for. Must be one of the values defined in the `billing` config option. */ plans?: (keyof Config['billing'])[]; } ``` ### CreateUsageRecordOptions * description The description of the app usage record. ```ts string ``` * idempotencyKey ```ts string ``` * isTest Whether to use the test mode. This prevents the credit card from being charged. ```ts boolean ``` * price The price of the app usage record. ```ts { amount: number; currencyCode: string; } ``` * subscriptionLineItemId ```ts string ``` ```ts export interface CreateUsageRecordOptions { /** * The description of the app usage record. */ description: string; /** * The price of the app usage record. */ price: { /** * The amount to charge for this usage record. */ amount: number; /** * The currency code for this usage record. */ currencyCode: string; }; /** * Whether to use the test mode. This prevents the credit card from being charged. */ isTest: boolean; /* * Defines the usage pricing plan the merchant is subscribed to. */ subscriptionLineItemId?: string; /* * A unique key generated to avoid duplicate charges. */ idempotencyKey?: string; } ``` ### RequestBillingOptions * isTest Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged. ```ts boolean ``` * plan The plan to request. Must be one of the values defined in the \`billing\` config option. ```ts keyof Config["billing"] ``` * returnUrl The URL to return to after the merchant approves the payment. ```ts string ``` ```ts export interface RequestBillingOptions extends Omit { /** * The plan to request. Must be one of the values defined in the `billing` config option. */ plan: keyof Config['billing']; /** * Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged. */ isTest?: boolean; /** * The URL to return to after the merchant approves the payment. */ returnUrl?: string; } ``` ### RequireBillingOptions * isTest Whether to include charges that were created on test mode. Test shops and demo shops cannot be charged. ```ts boolean ``` * onFailure How to handle the request if the shop doesn't have an active payment for any plan. ```ts (error: any) => Promise ``` * plans The plans to check for. Must be one of the values defined in the \`billing\` config option. ```ts (keyof Config["billing"])[] ``` ```ts export interface RequireBillingOptions extends Omit { /** * The plans to check for. Must be one of the values defined in the `billing` config option. */ plans: (keyof Config['billing'])[]; /** * How to handle the request if the shop doesn't have an active payment for any plan. */ onFailure: (error: any) => Promise; } ``` ### UpdateUsageCappedAmountOptions * cappedAmount The maximum charge for the usage billing plan. ```ts { amount: number; currencyCode: string; } ``` * subscriptionLineItemId The subscription line item ID to update. ```ts string ``` ```ts export interface UpdateUsageCappedAmountOptions { /** * The subscription line item ID to update. */ subscriptionLineItemId: string; /** * The maximum charge for the usage billing plan. */ cappedAmount: { /** * The amount to update. */ amount: number; /** * The currency code to update. */ currencyCode: string; }; } ``` ### EnsureCORSFunction ```ts export interface EnsureCORSFunction { (response: Response): Response; } ``` ### Session Stores App information from logged in merchants so they can make authenticated requests to the Admin API. * id The unique identifier for the session. ```ts string ``` * shop The Shopify shop domain, such as \`example.myshopify.com\`. ```ts string ``` * state The state of the session. Used for the OAuth authentication code flow. ```ts string ``` * isOnline Whether the access token in the session is online or offline. ```ts boolean ``` * scope The desired scopes for the access token, at the time the session was created. ```ts string ``` * expires The date the access token expires. ```ts Date ``` * accessToken The access token for the session. ```ts string ``` * onlineAccessInfo Information on the user for the session. Only present for online sessions. ```ts OnlineAccessInfo ``` * isActive Whether the session is active. Active sessions have an access token that is not expired, and has has the given scopes if scopes is equal to a truthy value. ```ts (scopes: string | string[] | AuthScopes, withinMillisecondsOfExpiry?: number) => boolean ``` * isScopeChanged Whether the access token includes the given scopes if they are provided. ```ts (scopes: string | string[] | AuthScopes) => boolean ``` * isScopeIncluded Whether the access token includes the given scopes. ```ts (scopes: string | string[] | AuthScopes) => boolean ``` * isExpired Whether the access token is expired. ```ts (withinMillisecondsOfExpiry?: number) => boolean ``` * toObject Converts an object with data into a Session. ```ts () => SessionParams ``` * equals Checks whether the given session is equal to this session. ```ts (other: Session) => boolean ``` * toPropertyArray Converts the session into an array of key-value pairs. ```ts (returnUserData?: boolean) => [string, string | number | boolean][] ``` ```ts export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has has the given * scopes if scopes is equal to a truthy value. */ public isActive( scopes: AuthScopes | string | string[] | undefined, withinMillisecondsOfExpiry = 500, ): boolean { const hasAccessToken = Boolean(this.accessToken); const isTokenNotExpired = !this.isExpired(withinMillisecondsOfExpiry); const isScopeChanged = this.isScopeChanged(scopes); return !isScopeChanged && hasAccessToken && isTokenNotExpired; } /** * Whether the access token includes the given scopes if they are provided. */ public isScopeChanged( scopes: AuthScopes | string | string[] | undefined, ): boolean { if (typeof scopes === 'undefined') { return false; } return !this.isScopeIncluded(scopes); } /** * Whether the access token includes the given scopes. */ public isScopeIncluded(scopes: AuthScopes | string | string[]): boolean { const requiredScopes = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); const sessionScopes = new AuthScopes(this.scope); return sessionScopes.has(requiredScopes); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } ``` ### OnlineAccessInfo * associated\_user The user associated with the access token. ```ts OnlineAccessUser ``` * associated\_user\_scope The effective set of scopes for the session. ```ts string ``` * expires\_in How long the access token is valid for, in seconds. ```ts number ``` ```ts export interface OnlineAccessInfo { /** * How long the access token is valid for, in seconds. */ expires_in: number; /** * The effective set of scopes for the session. */ associated_user_scope: string; /** * The user associated with the access token. */ associated_user: OnlineAccessUser; } ``` ### OnlineAccessUser * account\_owner Whether the user is the account owner. ```ts boolean ``` * collaborator Whether the user is a collaborator. ```ts boolean ``` * email The user's email address. ```ts string ``` * email\_verified Whether the user has verified their email address. ```ts boolean ``` * first\_name The user's first name. ```ts string ``` * id The user's ID. ```ts number ``` * last\_name The user's last name. ```ts string ``` * locale The user's locale. ```ts string ``` ```ts export interface OnlineAccessUser { /** * The user's ID. */ id: number; /** * The user's first name. */ first_name: string; /** * The user's last name. */ last_name: string; /** * The user's email address. */ email: string; /** * Whether the user has verified their email address. */ email_verified: boolean; /** * Whether the user is the account owner. */ account_owner: boolean; /** * The user's locale. */ locale: string; /** * Whether the user is a collaborator. */ collaborator: boolean; } ``` ### AuthScopes A class that represents a set of access token scopes. * has Checks whether the current set of scopes includes the given one. ```ts (scope: string | string[] | AuthScopes) => boolean ``` * equals Checks whether the current set of scopes equals the given one. ```ts (otherScopes: string | string[] | AuthScopes) => boolean ``` * toString Returns a comma-separated string with the current set of scopes. ```ts () => string ``` * toArray Returns an array with the current set of scopes. ```ts (returnOriginalScopes?: boolean) => any[] ``` ```ts class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; private originalScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); this.originalScopes = scopeSet; } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray(returnOriginalScopes = false) { return returnOriginalScopes ? [...this.originalScopes] : [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } ``` ### SessionParams * \[key: string] ```ts any ``` * accessToken The access token for the session. ```ts string ``` * expires The date the access token expires. ```ts Date ``` * id The unique identifier for the session. ```ts string ``` * isOnline Whether the access token in the session is online or offline. ```ts boolean ``` * onlineAccessInfo Information on the user for the session. Only present for online sessions. ```ts OnlineAccessInfo | StoredOnlineAccessInfo ``` * scope The scopes for the access token. ```ts string ``` * shop The Shopify shop domain. ```ts string ``` * state The state of the session. Used for the OAuth authentication code flow. ```ts string ``` ```ts export interface SessionParams { /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain. */ shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ state: string; /** * Whether the access token in the session is online or offline. */ isOnline: boolean; /** * The scopes for the access token. */ scope?: string; /** * The date the access token expires. */ expires?: Date; /** * The access token for the session. */ accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ onlineAccessInfo?: OnlineAccessInfo | StoredOnlineAccessInfo; /** * Additional properties of the session allowing for extension */ [key: string]: any; } ``` ### StoredOnlineAccessInfo ```ts Omit & { associated_user: Partial; } ``` ### EmbeddedAdminContext * admin Methods for interacting with the GraphQL Admin API for the store that made the request. ```ts AdminApiContext ``` * billing Billing methods for this store, based on the plans defined in the \`billing\` config option. ```ts BillingContext ``` * cors A function that ensures the CORS headers are set correctly for the response. ```ts EnsureCORSFunction ``` * redirect A function that redirects the user to a new page, ensuring that the appropriate parameters are set for embedded apps. Returned only if \`isEmbeddedApp\` is \`true\`. ```ts RedirectFunction ``` * session The session for the user who made the request. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. Use this to get shop or user-specific data. ```ts Session ``` * sessionToken The decoded and validated session token for the request. Returned only if \`isEmbeddedApp\` is \`true\`. ```ts JwtPayload ``` ````ts export interface EmbeddedAdminContext extends AdminContextInternal { /** * The decoded and validated session token for the request. * * Returned only if `isEmbeddedApp` is `true`. * * {@link https://shopify.dev/docs/apps/auth/oauth/session-tokens#payload} * * @example * Using the decoded session token. * Get user-specific data using the `sessionToken` object. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken } = await authenticate.admin( * request * ); * return json(await getMyAppData({user: sessionToken.sub})); * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * useOnlineTokens: true, * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ sessionToken: JwtPayload; /** * A function that redirects the user to a new page, ensuring that the appropriate parameters are set for embedded * apps. * * Returned only if `isEmbeddedApp` is `true`. * * @example * Redirecting to an app route. * Use the `redirect` helper to safely redirect between pages. * ```ts * // /app/routes/admin/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { session, redirect } = await authenticate.admin(request); * return redirect("/"); * }; * ``` * * @example * Redirecting to a page in the Shopify Admin. * Redirects to a product page in the Shopify admin. Pass in a `target` option of `_top` or `_parent` to navigate in the current window, or `_blank` to open a new tab. * ```ts * // /app/routes/admin/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { session, redirect } = await authenticate.admin(request); * return redirect("shopify://admin/products/123456", { target: '_parent' }); * }; * ``` * * @example * Redirecting outside of the Admin embedded app page. * Pass in a `target` option of `_top` or `_parent` to navigate in the current window, or `_blank` to open a new tab. * ```ts * // /app/routes/admin/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { session, redirect } = await authenticate.admin(request); * return redirect("/", { target: '_parent' }); * }; * ``` */ redirect: RedirectFunction; } ```` ### RedirectFunction * url ```ts string ``` * init ```ts RedirectInit ``` TypedResponse\ ```ts TypedResponse ``` ```ts ( url: string, init?: RedirectInit, ) => TypedResponse ``` ### RedirectInit ```ts number | (ResponseInit & {target?: RedirectTarget}) ``` ### RedirectTarget ```ts '_self' | '_parent' | '_top' | '_blank' ``` ### ScopesContext * scopes Methods to manage scopes for the store that made the request. ```ts ScopesApiContext ``` ```ts export interface ScopesContext { /** * Methods to manage scopes for the store that made the request. */ scopes: ScopesApiContext; } ``` ### ScopesApiContext The Scopes API enables embedded apps and extensions to request merchant consent for access scopes. * query Queries Shopify to see what scopes have been granted ```ts () => Promise ``` * request Requests the merchant grant the provided scopes This method performs a redirect to the grant screen. ```ts (scopes: string[]) => Promise ``` * revoke Revokes the provided scopes Warning: This method throws an \[error]\(https\://shopify.dev/docs/api/admin-graphql/unstable/objects/AppRevokeAccessScopesAppRevokeScopeError) if the provided optional scopes contains a required scope. ```ts (scopes: string[]) => Promise ``` ````ts export interface ScopesApiContext { /** * Queries Shopify to see what scopes have been granted * * @returns {ScopesDetail} The scope details. * * @example * Query for granted scopes. * Call `scopes.query` to get scope details. * ```ts * // /app._index.tsx * import { authenticate } from "../shopify.server"; * import { json } from "@remix-run/node"; * * export const loader = async ({ request }) => { * const { scopes } = await authenticate.admin(request); * const { required, optional, granted } = await scopes.query(); * * if (granted.includes("write_products")) { * // do something * } * * return null * }; * * ``` */ query: () => Promise; /** * Requests the merchant grant the provided scopes * * This method performs a redirect to the grant screen. * * @example * Ask the merchant to grant the provided scopes. * Call `scopes.request` to request optional scopes. * ```ts * // /app/routes/app.request.tsx * import { authenticate } from "../shopify.server"; * * // Example of an action to request optional scopes * export const action = async ({ request }) => { * const { scopes } = await authenticate.admin(request); * const { granted } = await scopes.query(); * * if (!granted.includes("write_products")) { * await scopes.request(["write_products"]); * } * * return null * }; * ``` */ request: (scopes: Scope[]) => Promise; /** * Revokes the provided scopes * * Warning: This method throws an [error](https://shopify.dev/docs/api/admin-graphql/unstable/objects/AppRevokeAccessScopesAppRevokeScopeError) if the provided optional scopes contains a required scope. * * @example * Revoke optional scopes. * Call `scopes.revoke` to revoke optional scopes. * ```ts * // /app._index.tsx * import { authenticate } from "../shopify.server"; * import { json } from "@remix-run/node"; * * // Example of an action to POST optional scopes to revoke * export const action = async ({ request }) => { * const { scopes } = await authenticate.admin(request); * const { granted } = await scopes.query(); * * if (granted.includes("write_products")) { * const revokedResponse = await scopes.revoke(["write_products"]); * return json(revokedResponse); * } * * return null * }; * * ``` */ revoke: (scopes: Scope[]) => Promise; } ```` ### ScopesDetail * granted The scopes that have been granted on the shop for this app ```ts string[] ``` * optional The optional scopes that the app has declared in its configuration ```ts string[] ``` * required The required scopes that the app has declared in its configuration ```ts string[] ``` ```ts export interface ScopesDetail { /** * The scopes that have been granted on the shop for this app */ granted: Scope[]; /** * The required scopes that the app has declared in its configuration */ required: Scope[]; /** * The optional scopes that the app has declared in its configuration */ optional: Scope[]; } ``` ### ScopesRevokeResponse * revoked The scopes that have been revoked on the shop for this app ```ts string[] ``` ```ts export interface ScopesRevokeResponse { /** * The scopes that have been revoked on the shop for this app */ revoked: Scope[]; } ``` ### AuthenticateFlow * request ```ts Request ``` Promise\ ```ts Promise ``` ```ts (request: Request) => Promise ``` ### FlowContext * admin An admin context for the Flow request. Returned only if there is a session for the shop. ```ts AdminApiContext ``` * payload The payload from the Flow request. ```ts any ``` * session A session with an offline token for the shop. Returned only if there is a session for the shop. ```ts Session ``` ````ts export interface FlowContext { /** * A session with an offline token for the shop. * * Returned only if there is a session for the shop. * * @example * Shopify session for the Flow request. * Use the session associated with this request. * ```ts * // /app/routes/flow.tsx * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { session, admin } = await authenticate.flow(request); * * console.log(session.id) * * return new Response(); * }; * ``` */ session: Session; /** * The payload from the Flow request. * * @example * Flow payload. * Get the request's POST payload. * ```ts * // /app/routes/flow.tsx * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { payload } = await authenticate.flow(request); * return new Response(); * }; * ``` */ payload: any; /** * An admin context for the Flow request. * * Returned only if there is a session for the shop. * * @example * Flow admin context. * Use the `admin` object in the context to interact with the Admin API. * ```ts * // /app/routes/flow.tsx * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.flow(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({ data: productData.data }); * } * ``` */ admin: AdminApiContext; } ```` ### AuthenticateFulfillmentService * request ```ts Request ``` Promise\ ```ts Promise ``` ```ts ( request: Request, ) => Promise ``` ### FulfillmentServiceContext * admin An admin context for the fulfillment service request. Returned only if there is a session for the shop. ```ts AdminApiContext ``` * payload The payload from the fulfillment service request. ```ts FulfillmentServicePayload ``` * session A session with an offline token for the shop. Returned only if there is a session for the shop. ```ts Session ``` ````ts export interface FulfillmentServiceContext { /** * A session with an offline token for the shop. * * Returned only if there is a session for the shop. * @example * Shopify session for the fulfillment service notification request. * Use the session associated with this request. * ```ts * // /app/routes/fulfillment_service_notification.tsx * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { session, admin } = await authenticate.fulfillmentService(request); * * console.log(session.id) * * return new Response(); * }; * ``` * */ session: Session; /** * * An admin context for the fulfillment service request. * * Returned only if there is a session for the shop. * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin, session } = await authenticate.fulfillmentService(request); * * console.log(session.id) * * return new Response(); * } * ``` */ admin: AdminApiContext; /** * The payload from the fulfillment service request. * * @example * Fulfillment service request payload. * Get the request's POST payload. * ```ts * /app/routes/fulfillment_order_notification.ts * import { ActionFunction } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action: ActionFunction = async ({ request }) => { * const { payload } = await authenticate.fulfillmentService(request); * if(payload.kind === 'FULFILLMENT_REQUEST') { * // handle fulfillment request * } else if (payload.kind === 'CANCELLATION_REQUEST') { * // handle cancellation request * }; * return new Response(); * ``` */ payload: FulfillmentServicePayload; } ```` ### FulfillmentServicePayload ```ts Record & { kind: string; } ``` ### AuthenticatePublic * appProxy Authenticate a request from an app proxy ```ts AuthenticateAppProxy ``` * checkout Authenticate a request from a checkout extension ```ts AuthenticateCheckout ``` * customerAccount Authenticate a request from a customer account extension ```ts AuthenticateCustomerAccount ``` * pos Authenticate a request from a POS UI extension ```ts AuthenticatePOS ``` ````ts export interface AuthenticatePublic { /** * Authenticate a request from a checkout extension * * @example * Authenticating a checkout extension request * ```ts * // /app/routes/public/widgets.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken, cors } = await authenticate.public.checkout( * request, * ); * return cors(json({my: "data", shop: sessionToken.dest})); * }; * ``` */ checkout: AuthenticateCheckout; /** * Authenticate a request from an app proxy * * @example * Authenticating an app proxy request * ```ts * // /app/routes/public/widgets.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * await authenticate.public.appProxy( * request, * ); * * const {searchParams} = new URL(request.url); * const shop = searchParams.get("shop"); * const customerId = searchParams.get("logged_in_customer_id") * * return json({my: "data", shop, customerId}); * }; * ``` */ appProxy: AuthenticateAppProxy; /** * Authenticate a request from a customer account extension * * @example * Authenticating a customer account extension request * ```ts * // /app/routes/public/widgets.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken, cors } = await authenticate.public.customerAccount( * request, * ); * return cors(json({my: "data", shop: sessionToken.dest})); * }; * ``` */ customerAccount: AuthenticateCustomerAccount; /** * Authenticate a request from a POS UI extension * * @example * Authenticating a POS UI extension request * ```ts * // /app/routes/public/widgets.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken, cors } = await authenticate.public.pos( * request, * ); * return cors(json({my: "data", shop: sessionToken.dest})); * }; * ``` */ pos: AuthenticatePOS; } ```` ### AuthenticateAppProxy * request ```ts Request ``` Promise\ ```ts Promise ``` ```ts ( request: Request, ) => Promise ``` ### AppProxyContext * admin No session is available for the shop that made this request. Therefore no methods for interacting with the GraphQL Admin API are available. ```ts undefined ``` * liquid A utility for creating a Liquid Response. ```ts LiquidResponseFunction ``` * session No session is available for the shop that made this request. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. ```ts undefined ``` * storefront No session is available for the shop that made this request. Therefore no method for interacting with the Storefront API is available. ```ts undefined ``` ```ts export interface AppProxyContext extends Context { /** * No session is available for the shop that made this request. * * This comes from the session storage which `shopifyApp` uses to store sessions in your database of choice. */ session: undefined; /** * No session is available for the shop that made this request. * Therefore no methods for interacting with the GraphQL Admin API are available. */ admin: undefined; /** * No session is available for the shop that made this request. * Therefore no method for interacting with the Storefront API is available. */ storefront: undefined; } ``` ### LiquidResponseFunction * body ```ts string ``` * initAndOptions ```ts number | (ResponseInit & Options) ``` Response ```ts Response ``` ```ts ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response ``` ### AppProxyContextWithSession * admin Methods for interacting with the GraphQL Admin API for the store that made the request. ```ts AdminApiContext ``` * liquid A utility for creating a Liquid Response. ```ts LiquidResponseFunction ``` * session The session for the shop that made the request. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. Use this to get shop or user-specific data. ```ts Session ``` * storefront Method for interacting with the Shopify Storefront Graphql API for the store that made the request. ```ts StorefrontContext ``` ````ts export interface AppProxyContextWithSession extends Context { /** * The session for the shop that made the request. * * This comes from the session storage which `shopifyApp` uses to store sessions in your database of choice. * * Use this to get shop or user-specific data. * * @example * Using the session object. * Get the session for the shop that initiated the request to the app proxy. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppModelData } from "~/db/model.server"; * * export const loader = async ({ request }) => { * // Get the session for the shop that initiated the request to the app proxy. * const { session } = * await authenticate.public.appProxy(request); * * // Use the session data to make to queries to your database or additional requests. * return json( * await getMyAppModelData({shop: session.shop}) * ); * }; * ``` */ session: Session; /** * Methods for interacting with the GraphQL Admin API for the store that made the request. * * @example * Interacting with the Admin API. * Use the `admin` object to interact with the admin GraphQL API. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.public.appProxy(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({ data: productData.data }); * } * ``` */ admin: AdminApiContext; /** * Method for interacting with the Shopify Storefront Graphql API for the store that made the request. * * @example * Interacting with the Storefront API. * Use the `storefront` object to interact with the GraphQL API. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { storefront } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql( * `#graphql * query blogIds { * blogs(first: 10) { * edges { * node { * id * } * } * } * }` * ); * * return json(await response.json()); * } * ``` */ storefront: StorefrontContext; } ```` ### StorefrontContext * graphql Method for interacting with the Shopify Storefront GraphQL API If you're getting incorrect type hints in the Shopify template, follow \[these instructions]\(https\://github.com/Shopify/shopify-app-template-remix/tree/main#incorrect-graphql-hints). ```ts GraphQLClient ``` ````ts export interface StorefrontContext { /** * Method for interacting with the Shopify Storefront GraphQL API * * If you're getting incorrect type hints in the Shopify template, follow [these instructions](https://github.com/Shopify/shopify-app-template-remix/tree/main#incorrect-graphql-hints). * * {@link https://shopify.dev/docs/api/storefront} * * @example * Querying the GraphQL API. * Use `storefront.graphql` to make query / mutation requests. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { storefront } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` * * @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 { storefront } = await authenticate.public.appProxy(request); * * try { * const response = await storefront.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // { 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; } ```` ### AuthenticateCheckout * request ```ts Request ``` * options ```ts AuthenticateCheckoutOptions ``` Promise\ ```ts Promise ``` ```ts ( request: Request, options?: AuthenticateCheckoutOptions, ) => Promise ``` ### AuthenticateCheckoutOptions * corsHeaders ```ts string[] ``` ```ts export interface AuthenticateCheckoutOptions { corsHeaders?: string[]; } ``` ### CheckoutContext Authenticated Context for a checkout request * cors A function that ensures the CORS headers are set correctly for the response. ```ts EnsureCORSFunction ``` * sessionToken The decoded and validated session token for the request Refer to the OAuth docs for the \[session token payload]\(https\://shopify.dev/docs/apps/auth/oauth/session-tokens#payload). ```ts JwtPayload ``` ````ts export interface CheckoutContext { /** * The decoded and validated session token for the request * * Refer to the OAuth docs for the [session token payload](https://shopify.dev/docs/apps/auth/oauth/session-tokens#payload). * * @example * Using the decoded session token. * Get store-specific data using the `sessionToken` object. * ```ts * // app/routes/public/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken } = await authenticate.public.checkout( * request * ); * return json(await getMyAppData({shop: sessionToken.dest})); * }; * ``` */ sessionToken: JwtPayload; /** * A function that ensures the CORS headers are set correctly for the response. * * @example * Setting CORS headers for a public request. * Use the `cors` helper to ensure your app can respond to checkout extension requests. * ```ts * // app/routes/public/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken, cors } = await authenticate.public.checkout( * request, * { corsHeaders: ["X-My-Custom-Header"] } * ); * const data = await getMyAppData({shop: sessionToken.dest}); * return cors(json(data)); * }; * ``` */ cors: EnsureCORSFunction; } ```` ### AuthenticateCustomerAccount * request ```ts Request ``` * options ```ts AuthenticateCustomerAccountOptions ``` Promise\ ```ts Promise ``` ```ts ( request: Request, options?: AuthenticateCustomerAccountOptions, ) => Promise ``` ### AuthenticateCustomerAccountOptions * corsHeaders ```ts string[] ``` ```ts export interface AuthenticateCustomerAccountOptions { corsHeaders?: string[]; } ``` ### CustomerAccountContext Authenticated Context for a customer account extension request * cors A function that ensures the CORS headers are set correctly for the response. ```ts EnsureCORSFunction ``` * sessionToken The decoded and validated session token for the request Refer to the OAuth docs for the \[session token payload]\(https\://shopify.dev/docs/apps/auth/oauth/session-tokens#payload). ```ts JwtPayload ``` ````ts export interface CustomerAccountContext { /** * The decoded and validated session token for the request * * Refer to the OAuth docs for the [session token payload](https://shopify.dev/docs/apps/auth/oauth/session-tokens#payload). * * @example * Using the decoded session token. * Get store-specific data using the `sessionToken` object. * ```ts * // app/routes/public/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken } = await authenticate.public.customerAccount( * request * ); * return json(await getMyAppData({shop: sessionToken.dest})); * }; * ``` */ sessionToken: JwtPayload; /** * A function that ensures the CORS headers are set correctly for the response. * * @example * Setting CORS headers for a public request. * Use the `cors` helper to ensure your app can respond to customer account extension requests. * ```ts * // app/routes/public/my-route.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { sessionToken, cors } = await authenticate.public.customerAccount( * request, * { corsHeaders: ["X-My-Custom-Header"] } * ); * const data = await getMyAppData({shop: sessionToken.dest}); * return cors(json(data)); * }; * ``` */ cors: EnsureCORSFunction; } ```` ### AuthenticateWebhook * request ```ts Request ``` Promise\> ```ts Promise> ``` ```ts ( request: Request, ) => 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; } ```` ### RegisterWebhooks * options ```ts RegisterWebhooksOptions ``` Promise\ ```ts Promise ``` ```ts ( options: RegisterWebhooksOptions, ) => Promise ``` ### RegisterWebhooksOptions * session The Shopify session used to register webhooks using the Admin API. ```ts Session ``` ```ts export interface RegisterWebhooksOptions { /** * The Shopify session used to register webhooks using the Admin API. */ session: Session; } ``` ### SessionStorageType ```ts Config['sessionStorage'] extends SessionStorage ? Config['sessionStorage'] : SessionStorage ``` ### Unauthenticated * admin Get an admin context by passing a shop \*\*Warning\*\* This should only be used for Requests that do not originate from Shopify. You must do your own authentication before using this method. This method throws an error if there is no session for the shop. ```ts GetUnauthenticatedAdminContext ``` * storefront Get a storefront context by passing a shop \*\*Warning\*\* This should only be used for Requests that do not originate from Shopify. You must do your own authentication before using this method. This method throws an error if there is no session for the shop. ```ts GetUnauthenticatedStorefrontContext ``` ````ts export interface Unauthenticated { /** * Get an admin context by passing a shop * * **Warning** This should only be used for Requests that do not originate from Shopify. * You must do your own authentication before using this method. * This method throws an error if there is no session for the shop. * * @example * Responding to a request not controlled by Shopify. * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * const response = await admin.graphql("{ shop { name} }") * * return json(await response.json()); * } * ``` */ admin: GetUnauthenticatedAdminContext; /** * Get a storefront context by passing a shop * * **Warning** This should only be used for Requests that do not originate from Shopify. * You must do your own authentication before using this method. * This method throws an error if there is no session for the shop. * * @example * Responding to a request not controlled by Shopify * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {storefront} = await shopify.unauthenticated.storefront(shop); * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` */ storefront: GetUnauthenticatedStorefrontContext; } ```` ### GetUnauthenticatedAdminContext * shop ```ts string ``` Promise\ ```ts Promise ``` ```ts ( shop: string, ) => Promise ``` ### UnauthenticatedAdminContext * admin Methods for interacting with the GraphQL Admin API for the given store. ```ts AdminApiContext ``` * session The session for the given shop. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. This will always be an offline session. You can use to get shop-specific data. ```ts Session ``` ````ts export interface UnauthenticatedAdminContext { /** * The session for the given shop. * * This comes from the session storage which `shopifyApp` uses to store sessions in your database of choice. * * This will always be an offline session. You can use to get shop-specific data. * * @example * Using the offline session. * Get your app's shop-specific data using the returned offline `session` object. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const shop = getShopFromExternalRequest(request); * const { session } = await unauthenticated.admin(shop); * return json(await getMyAppData({shop: session.shop)); * }; * ``` */ session: Session; /** * Methods for interacting with the GraphQL Admin API for the given store. * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const shop = getShopFromExternalRequest(request); * const { admin } = await unauthenticated.admin(shop); * * 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 }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * export const unauthenticated = shopify.unauthenticated; * ``` */ admin: AdminApiContext; } ```` ### GetUnauthenticatedStorefrontContext * shop ```ts string ``` Promise\ ```ts Promise ``` ```ts ( shop: string, ) => Promise ``` ### UnauthenticatedStorefrontContext * session The session for the given shop. This comes from the session storage which \`shopifyApp\` uses to store sessions in your database of choice. This will always be an offline session. You can use this to get shop specific data. ```ts Session ``` * storefront Method for interacting with the Shopify GraphQL Storefront API for the given store. ```ts StorefrontContext ``` ````ts export interface UnauthenticatedStorefrontContext { /** * The session for the given shop. * * This comes from the session storage which `shopifyApp` uses to store sessions in your database of choice. * * This will always be an offline session. You can use this to get shop specific data. * * @example * Using the offline session. * Get your app's shop-specific data using the returned offline `session` object. * ```ts * // app/routes/**\/.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const shop = getShopFromExternalRequest(request); * const { session } = await unauthenticated.storefront(shop); * return json(await getMyAppData({shop: session.shop)); * }; * ``` */ session: Session; /** * Method for interacting with the Shopify GraphQL Storefront API for the given store. * * @example * Querying the GraphQL API. * Use `storefront.graphql` to make query / mutation requests. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const shop = getShopFromExternalRequest(request); * const { storefront } = await unauthenticated.storefront(shop); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` * * @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 shop = getShopFromExternalRequest(request); * const { storefront } = await unauthenticated.storefront(shop); * * try { * const response = await storefront.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // { 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 unauthenticated = shopify.unauthenticated; * ``` */ storefront: StorefrontContext; } ```` ### EnforceSessionStorage ```ts Base & { sessionStorage: SessionStorageType; } ``` ### Base * \#session ```ts Session ``` * session ```ts Session ``` * save ```ts ({ update }?: SaveArgs) => Promise ``` * saveAndUpdate ```ts () => Promise ``` * delete ```ts () => Promise ``` * serialize ```ts (saving?: boolean) => Body ``` * toJSON ```ts () => Body ``` * request ```ts (args: RequestArgs) => Promise> ``` ```ts export class Base { // For instance attributes [key: string]: any; public static Client: typeof RestClient; public static config: ConfigInterface; public static apiVersion: string; protected static resourceNames: ResourceNames[] = []; protected static primaryKey = 'id'; protected static customPrefix: string | null = null; protected static readOnlyAttributes: string[] = []; protected static hasOne: Record = {}; protected static hasMany: Record = {}; protected static paths: ResourcePath[] = []; public static setClassProperties({Client, config}: SetClassPropertiesArgs) { this.Client = Client; this.config = config; } protected static async baseFind({ session, urlIds, params, requireIds = false, }: BaseFindArgs): Promise> { if (requireIds) { const hasIds = Object.entries(urlIds).some(([_key, value]) => value); if (!hasIds) { throw new RestResourceError( 'No IDs given for request, cannot find path', ); } } const response = await this.request({ http_method: 'get', operation: 'get', session, urlIds, params, }); return { data: this.createInstancesFromResponse(session, response.body as Body), headers: response.headers, pageInfo: response.pageInfo, }; } protected static async request({ session, http_method, operation, urlIds, params, body, entity, }: RequestArgs): Promise> { const client = new this.Client({ session, apiVersion: this.apiVersion as ApiVersion, }); const path = this.getPath({http_method, operation, urlIds, entity}); const cleanParams: Record = {}; if (params) { for (const key in params) { if (params[key] !== null) { cleanParams[key] = params[key]; } } } switch (http_method) { case 'get': return client.get({path, query: cleanParams}); case 'post': return client.post({ path, query: cleanParams, data: body!, type: DataType.JSON, }); case 'put': return client.put({ path, query: cleanParams, data: body!, type: DataType.JSON, }); case 'delete': return client.delete({path, query: cleanParams}); default: throw new Error(`Unrecognized HTTP method "${http_method}"`); } } protected static getJsonBodyName(): string { return this.name.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); } protected static getPath({ http_method, operation, urlIds, entity, }: GetPathArgs): string { let match: string | null = null; let specificity = -1; const potentialPaths: ResourcePath[] = []; this.paths.forEach((path: ResourcePath) => { if ( http_method !== path.http_method || operation !== path.operation || path.ids.length <= specificity ) { return; } potentialPaths.push(path); let pathUrlIds: IdSet = {...urlIds}; path.ids.forEach((id) => { if (!pathUrlIds[id] && entity && entity[id]) { pathUrlIds[id] = entity[id]; } }); pathUrlIds = Object.entries(pathUrlIds).reduce( (acc: IdSet, [key, value]: [string, string | number | null]) => { if (value) { acc[key] = value; } return acc; }, {}, ); // If we weren't given all of the path's required ids, we can't use it const diff = path.ids.reduce( (acc: string[], id: string) => (pathUrlIds[id] ? acc : acc.concat(id)), [], ); if (diff.length > 0) { return; } specificity = path.ids.length; match = path.path.replace( /(<([^>]+)>)/g, (_m1, _m2, id) => `${pathUrlIds[id]}`, ); }); if (!match) { const pathOptions = potentialPaths.map((path) => path.path); throw new RestResourceError( `Could not find a path for request. If you are trying to make a request to one of the following paths, ensure all relevant IDs are set. :\n - ${pathOptions.join( '\n - ', )}`, ); } if (this.customPrefix) { return `${this.customPrefix}/${match}`; } else { return match; } } protected static createInstancesFromResponse( session: Session, data: Body, ): T[] { let instances: T[] = []; this.resourceNames.forEach((resourceName) => { const singular = resourceName.singular; const plural = resourceName.plural; if (data[plural] || Array.isArray(data[singular])) { instances = instances.concat( (data[plural] || data[singular]).reduce( (acc: T[], entry: Body) => acc.concat(this.createInstance(session, entry)), [], ), ); } else if (data[singular]) { instances.push(this.createInstance(session, data[singular])); } }); return instances; } protected static createInstance( session: Session, data: Body, prevInstance?: T, ): T { const instance: T = prevInstance ? prevInstance : new (this as any)({session}); if (data) { instance.setData(data); } return instance; } #session: Session; get session(): Session { return this.#session; } constructor({session, fromData}: BaseConstructorArgs) { this.#session = session; if (fromData) { this.setData(fromData); } } public async save({update = false}: SaveArgs = {}): Promise { const {primaryKey, resourceNames} = this.resource(); const method = this[primaryKey] ? 'put' : 'post'; const data = this.serialize(true); const response = await this.resource().request({ http_method: method, operation: method, session: this.session, urlIds: {}, body: {[this.resource().getJsonBodyName()]: data}, entity: this, }); const flattenResourceNames: string[] = resourceNames.reduce( (acc, obj) => { return acc.concat(Object.values(obj)); }, [], ); const matchResourceName = Object.keys(response.body as Body).filter( (key: string) => flattenResourceNames.includes(key), ); const body: Body | undefined = (response.body as Body)[ matchResourceName[0] ]; if (update && body) { this.setData(body); } } public async saveAndUpdate(): Promise { await this.save({update: true}); } public async delete(): Promise { await this.resource().request({ http_method: 'delete', operation: 'delete', session: this.session, urlIds: {}, entity: this, }); } public serialize(saving = false): Body { const {hasMany, hasOne, readOnlyAttributes} = this.resource(); return Object.entries(this).reduce((acc: Body, [attribute, value]) => { if ( ['#session'].includes(attribute) || (saving && readOnlyAttributes.includes(attribute)) ) { return acc; } if (attribute in hasMany && value) { acc[attribute] = value.reduce((attrAcc: Body, entry: Base) => { return attrAcc.concat(this.serializeSubAttribute(entry, saving)); }, []); } else if (attribute in hasOne && value) { acc[attribute] = this.serializeSubAttribute(value, saving); } else { acc[attribute] = value; } return acc; }, {}); } public toJSON(): Body { return this.serialize(); } public request(args: RequestArgs) { return this.resource().request(args); } protected setData(data: Body): void { const {hasMany, hasOne} = this.resource(); Object.entries(data).forEach(([attribute, val]) => { if (attribute in hasMany) { const HasManyResource: typeof Base = hasMany[attribute]; this[attribute] = []; val.forEach((entry: Body) => { const obj = new HasManyResource({session: this.session}); if (entry) { obj.setData(entry); } this[attribute].push(obj); }); } else if (attribute in hasOne) { const HasOneResource: typeof Base = hasOne[attribute]; const obj = new HasOneResource({session: this.session}); if (val) { obj.setData(val); } this[attribute] = obj; } else { this[attribute] = val; } }); } protected resource(): typeof Base { return this.constructor as unknown as typeof Base; } private serializeSubAttribute(attribute: Base, saving: boolean): Body { return attribute.serialize ? attribute.serialize(saving) : this.resource() .createInstance(this.session, attribute) .serialize(saving); } } ``` ### SaveArgs * update ```ts boolean ``` ```ts interface SaveArgs { update?: boolean; } ``` ### Body ```ts Record ``` ### RequestArgs * body ```ts Body | null ``` * entity ```ts Base | null ``` * http\_method ```ts string ``` * operation ```ts string ``` * params ```ts ParamSet ``` * requireIds ```ts boolean ``` * session ```ts Session ``` * urlIds ```ts IdSet ``` ```ts interface RequestArgs extends BaseFindArgs { http_method: string; operation: string; body?: Body | null; entity?: Base | null; } ``` ### ParamSet ```ts Record ``` ### IdSet ```ts Record ``` ### RestRequestReturn * body ```ts T ``` * headers ```ts Headers ``` * pageInfo ```ts PageInfo ``` ```ts export interface RestRequestReturn { body: T; headers: Headers; pageInfo?: PageInfo; } ``` ### PageInfo * fields ```ts string[] ``` * limit ```ts string ``` * nextPage ```ts PageInfoParams ``` * nextPageUrl ```ts string ``` * previousPageUrl ```ts string ``` * prevPage ```ts PageInfoParams ``` ```ts export interface PageInfo { limit: string; fields?: string[]; previousPageUrl?: string; nextPageUrl?: string; prevPage?: PageInfoParams; nextPage?: PageInfoParams; } ``` ### PageInfoParams * path ```ts string ``` * query ```ts SearchParams ``` ```ts export interface PageInfoParams { path: string; query: SearchParams; } ``` ### SingleMerchantApp ```ts ShopifyAppBase & ShopifyAppLogin ``` ### ShopifyAppBase * addDocumentResponseHeaders Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ```ts AddDocumentResponseHeaders ``` * authenticate Ways to authenticate requests from different surfaces across Shopify. ```ts Authenticate ``` * registerWebhooks Register shop-specific webhook subscriptions using the Admin GraphQL API. In many cases defining app-specific webhooks in the \`shopify.app.toml\` will be sufficient and easier to manage. Please see: You should only use this if you need shop-specific webhooks. ```ts RegisterWebhooks ``` * sessionStorage The \`SessionStorage\` instance you passed in as a config option. ```ts SessionStorageType ``` * unauthenticated Ways to get Contexts from requests that do not originate from Shopify. ```ts Unauthenticated ``` ````ts export interface ShopifyAppBase { /** * The `SessionStorage` instance you passed in as a config option. * * @example * Storing sessions with Prisma. * Import the `@shopify/shopify-app-session-storage-prisma` package to store sessions in your Prisma database. * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; * import prisma from "~/db.server"; * * const shopify = shopifyApp({ * sessionStorage: new PrismaSessionStorage(prisma), * // ...etc * }) * * // shopify.sessionStorage is an instance of PrismaSessionStorage * ``` */ sessionStorage?: SessionStorageType; /** * Adds the required Content Security Policy headers for Shopify apps to the given Headers object. * * {@link https://shopify.dev/docs/apps/store/security/iframe-protection} * * @example * Return headers on all requests. * Add headers to all HTML requests by calling `shopify.addDocumentResponseHeaders` in `entry.server.tsx`. * * ``` * // ~/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; * ``` * * ```ts * // entry.server.tsx * import { addDocumentResponseHeaders } from "~/shopify.server"; * * export default function handleRequest( * request: Request, * responseStatusCode: number, * responseHeaders: Headers, * remixContext: EntryContext * ) { * const markup = renderToString( * * ); * * responseHeaders.set("Content-Type", "text/html"); * addDocumentResponseHeaders(request, responseHeaders); * * return new Response("" + markup, { * status: responseStatusCode, * headers: responseHeaders, * }); * } * ``` */ addDocumentResponseHeaders: AddDocumentResponseHeaders; /** * Register shop-specific webhook subscriptions using the Admin GraphQL API. * * In many cases defining app-specific webhooks in the `shopify.app.toml` will be sufficient and easier to manage. Please see: * * {@link https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-vs-shop-specific-subscriptions} * * You should only use this if you need shop-specific webhooks. * * @example * Registering shop-specific webhooks after install * Trigger the registration to create the shop-specific webhook subscriptions after a merchant installs your app using the `afterAuth` hook. Learn more about [subscribing to webhooks.](https://shopify.dev/docs/api/shopify-app-remix/v3/guide-webhooks) * ```ts * // app/shopify.server.ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * webhooks: { * PRODUCTS_CREATE: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks/products/create", * }, * }, * hooks: { * afterAuth: async ({ session }) => { * // Register webhooks for the shop * // In this example, every shop will have these webhooks * // You could wrap this in some custom shop specific conditional logic if needed * shopify.registerWebhooks({ session }); * }, * }, * // ...etc * }); * ``` */ registerWebhooks: RegisterWebhooks; /** * Ways to authenticate requests from different surfaces across Shopify. * * @example * Authenticate Shopify requests. * Use the functions in `authenticate` to validate requests coming from Shopify. * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); * const response = admin.graphql(`{ shop { name } }`) * * return json(await response.json()); * } * ``` */ authenticate: Authenticate; /** * Ways to get Contexts from requests that do not originate from Shopify. * * @example * Using unauthenticated contexts. * Create contexts for requests that don't come from Shopify. * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * const response = admin.graphql(`{ shop { currencyCode } }`) * * return json(await response.json()); * } * ``` */ unauthenticated: Unauthenticated; } ```` ### ShopifyAppLogin * login Log a merchant in, and redirect them to the app root. Will redirect the merchant to authentication if a shop is present in the URL search parameters or form data. This function won't be present when the \`distribution\` config option is set to \`AppDistribution.ShopifyAdmin\`, because Admin apps aren't allowed to show a login page. ```ts Login ``` ````ts export interface ShopifyAppLogin { /** * Log a merchant in, and redirect them to the app root. Will redirect the merchant to authentication if a shop is * present in the URL search parameters or form data. * * This function won't be present when the `distribution` config option is set to `AppDistribution.ShopifyAdmin`, * because Admin apps aren't allowed to show a login page. * * @example * Creating a login page. * Use `shopify.login` to create a login form, in a route that can handle GET and POST requests. * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/auth/login.tsx * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const errors = shopify.login(request); * * return json(errors); * } * * export async function action({ request }: ActionFunctionArgs) { * const errors = shopify.login(request); * * return json(errors); * } * * export default function Auth() { * const actionData = useActionData(); * const [shop, setShop] = useState(""); * * return ( * * *
* * * Login * * * * *
*
*
* ); * } * ``` */ login: Login; } ```` ### Login * request ```ts Request ``` Promise\ ```ts Promise ``` ```ts (request: Request) => Promise ``` ### LoginError * shop ```ts LoginErrorType ``` ```ts export interface LoginError { shop?: LoginErrorType; } ``` ### LoginErrorType * MissingShop ```ts MISSING_SHOP ``` * InvalidShop ```ts INVALID_SHOP ``` ```ts export enum LoginErrorType { MissingShop = 'MISSING_SHOP', InvalidShop = 'INVALID_SHOP', } ``` ### AppStoreApp ```ts ShopifyAppBase & ShopifyAppLogin ``` ### AppConfigArg * \_logDisabledFutureFlags Whether to log disabled future flags at startup. ```ts boolean ``` * adminApiAccessToken An app-wide API access token. Only applies to custom apps. ```ts string ``` * apiKey The API key for your app. Also known as Client ID in your Partner Dashboard. ```ts string ``` * apiSecretKey The API secret key for your app. Also known as Client Secret in your Partner Dashboard. ```ts string ``` * apiVersion What version of Shopify's Admin API's would you like to use. ```ts ApiVersion ``` * appUrl The URL your app is running on. The \`@shopify/cli\` provides this URL as \`process.env.SHOPIFY\_APP\_URL\`. For development this is probably a tunnel URL that points to your local machine. If this is a production app, this is your production URL. ```ts string ``` * authPathPrefix A path that Shopify can reserve for auth related endpoints. This must match a $ route in your Remix app. That route must export a loader function that calls \`shopify.authenticate.admin(request)\`. ```ts string ``` * billing Billing configurations for the app. ```ts BillingConfig ``` * customShopDomains Override values for Shopify shop domains. ```ts (string | RegExp)[] ``` * distribution How your app is distributed. Default is \`AppDistribution.AppStore\`. AppStore should be used for public apps that are distributed in the Shopify App Store. SingleMerchant should be used for custom apps managed in the Partner Dashboard. ShopifyAdmin should be used for apps that are managed in the merchant's Shopify Admin. ```ts AppDistribution ``` * future Features that will be introduced in future releases of this package. You can opt in to these features by setting the corresponding flags. By doing so, you can prepare for future releases in advance and provide feedback on the new features. ```ts Future ``` * hooks Functions to call at key places during your apps lifecycle. These functions are called in the context of the request that triggered them. This means you can access the session. ```ts HooksConfig ``` * isEmbeddedApp Does your app render embedded inside the Shopify Admin or on its own. Unless you have very specific needs, this should be true. ```ts boolean ``` * isTesting Whether the app is initialised for local testing. ```ts boolean ``` * logger Customization options for Shopify logs. ```ts { log?: LogFunction; level?: LogSeverity; httpRequests?: boolean; timestamps?: boolean; } ``` * privateAppStorefrontAccessToken An app-wide API access token for the storefront API. Only applies to custom apps. ```ts string ``` * restResources REST resources to access the Admin API. You can import these from \`@shopify/shopify-api/rest/admin/\*\`. ```ts Resources ``` * scopes The scopes your app needs to access the API. Not required if using Shopify managed installation. ```ts string[] | AuthScopes ``` * sessionStorage An adaptor for storing sessions in your database of choice. Shopify provides multiple session storage adaptors and you can create your own. Optional for apps created in the Shopify Admin. ```ts Storage ``` * useOnlineTokens Whether your app use online or offline tokens. If your app uses online tokens, then both online and offline tokens will be saved to your database. This ensures your app can perform background jobs. ```ts boolean ``` * userAgentPrefix The user agent prefix to use for API requests. ```ts string ``` * webhooks The config for the shop-specific webhooks your app needs. Use this to configure shop-specific webhooks. In many cases defining app-specific webhooks in the \`shopify.app.toml\` will be sufficient and easier to manage. Please see: You should only use this if you need shop-specific webhooks. If you do need shop-specific webhooks this can be in used in conjunction with the afterAuth hook, loaders or processes such as background jobs. ```ts WebhookConfig ``` ````ts export interface AppConfigArg< Storage extends SessionStorage = SessionStorage, Future extends FutureFlagOptions = FutureFlagOptions, > extends Omit< ApiConfigArg>, | 'hostName' | 'hostScheme' | 'isEmbeddedApp' | 'apiVersion' | 'isCustomStoreApp' | 'future' > { /** * The URL your app is running on. * * The `@shopify/cli` provides this URL as `process.env.SHOPIFY_APP_URL`. For development this is probably a tunnel URL that points to your local machine. If this is a production app, this is your production URL. */ appUrl: string; /** * An adaptor for storing sessions in your database of choice. * * Shopify provides multiple session storage adaptors and you can create your own. * * Optional for apps created in the Shopify Admin. * * {@link https://github.com/Shopify/shopify-app-js/blob/main/README.md#session-storage-options} * * @example * Storing sessions with Prisma. * Add the `@shopify/shopify-app-session-storage-prisma` package to use the Prisma session storage. * ```ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; * * import prisma from "~/db.server"; * * const shopify = shopifyApp({ * // ... etc * sessionStorage: new PrismaSessionStorage(prisma), * }); * export default shopify; * ``` */ sessionStorage?: Storage; /** * Whether your app use online or offline tokens. * * If your app uses online tokens, then both online and offline tokens will be saved to your database. This ensures your app can perform background jobs. * * {@link https://shopify.dev/docs/apps/auth/oauth/access-modes} * * @defaultValue `false` */ useOnlineTokens?: boolean; /** * The config for the shop-specific webhooks your app needs. * * Use this to configure shop-specific webhooks. In many cases defining app-specific webhooks in the `shopify.app.toml` will be sufficient and easier to manage. Please see: * * {@link https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-vs-shop-specific-subscriptions} * * You should only use this if you need shop-specific webhooks. If you do need shop-specific webhooks this can be in used in conjunction with the afterAuth hook, loaders or processes such as background jobs. * * @example * Registering shop-specific webhooks. * ```ts * // app/shopify.server.ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * webhooks: { * PRODUCTS_CREATE: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks/products/create", * }, * }, * hooks: { * afterAuth: async ({ session }) => { * // Register webhooks for the shop * // In this example, every shop will have these webhooks * // But you could wrap this in some custom shop specific conditional logic * shopify.registerWebhooks({ session }); * } * }, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Registering app-specific webhooks (Recommended) * ```toml * # shopify.app.toml * [webhooks] * api_version = "2024-07" * [[webhooks.subscriptions]] * topics = ["products/create"] * uri = "/webhooks/products/create" * * ``` * * @example * Authenticating a webhook request * * ```ts * // /app/routes/webhooks.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session, payload } = 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 the webhook * console.log(`${TOPIC} webhook received with`, JSON.stringify(payload)) * * throw new Response(); * }; * ``` */ webhooks?: WebhookConfig; /** * Functions to call at key places during your apps lifecycle. * * These functions are called in the context of the request that triggered them. This means you can access the session. * * @example * Seeding your database custom data when a merchant installs your app. * ```ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { seedStoreData } from "~/db/seeds" * * const shopify = shopifyApp({ * hooks: { * afterAuth: async ({ session }) => { * seedStoreData({session}) * } * }, * // ...etc * }); * ``` */ hooks?: HooksConfig; /** * Does your app render embedded inside the Shopify Admin or on its own. * * Unless you have very specific needs, this should be true. * * @defaultValue `true` */ isEmbeddedApp?: boolean; /** * How your app is distributed. Default is `AppDistribution.AppStore`. * * AppStore should be used for public apps that are distributed in the Shopify App Store. * SingleMerchant should be used for custom apps managed in the Partner Dashboard. * ShopifyAdmin should be used for apps that are managed in the merchant's Shopify Admin. * * {@link https://shopify.dev/docs/apps/distribution} */ distribution?: AppDistribution; /** * What version of Shopify's Admin API's would you like to use. * * {@link https://shopify.dev/docs/api/} * * @example * Using a specific API Version * ```ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * apiVersion: ApiVersion.July25, * }); * ``` */ apiVersion: ApiVersion; /** * A path that Shopify can reserve for auth related endpoints. * * This must match a $ route in your Remix app. That route must export a loader function that calls `shopify.authenticate.admin(request)`. * * @default `"/auth"` * * @example * Using an authPathPrefix * ```ts * // /app/shopify.server.ts * import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * authPathPrefix: "/auth", * }); * export default shopify; * export const authenticate = shopify.authenticate; * * // /app/routes/auth/$.jsx * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * await authenticate.admin(request); * * return null * } * ``` */ authPathPrefix?: string; /** * Features that will be introduced in future releases of this package. * * You can opt in to these features by setting the corresponding flags. By doing so, you can prepare for future * releases in advance and provide feedback on the new features. */ future?: Future; } ```` ### BillingConfig Billing configuration options, indexed by an app-specific plan name. * \[plan: string] ```ts BillingConfigItem ``` ```ts export interface BillingConfig { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } ``` ### BillingConfigItem ```ts BillingConfigOneTimePlan | BillingConfigSubscriptionLineItemPlan ``` ### BillingConfigOneTimePlan * amount Amount to charge for this plan. ```ts number ``` * currencyCode Currency code for this plan. ```ts string ``` * interval Interval for this plan. Must be set to \`OneTime\`. ```ts BillingInterval.OneTime ``` ```ts export interface BillingConfigOneTimePlan extends BillingConfigPlan { /** * Interval for this plan. * * Must be set to `OneTime`. */ interval: BillingInterval.OneTime; } ``` ### BillingInterval * OneTime ```ts ONE_TIME ``` * Every30Days ```ts EVERY_30_DAYS ``` * Annual ```ts ANNUAL ``` * Usage ```ts USAGE ``` ```ts export declare enum BillingInterval { OneTime = "ONE_TIME", Every30Days = "EVERY_30_DAYS", Annual = "ANNUAL", Usage = "USAGE" } ``` ### BillingConfigSubscriptionLineItemPlan * lineItems The line items for this plan. ```ts (BillingConfigRecurringLineItem | BillingConfigUsageLineItem)[] ``` * replacementBehavior The replacement behavior to use for this plan. ```ts BillingReplacementBehavior ``` * trialDays How many trial days to give before charging for this plan. ```ts number ``` ```ts export interface BillingConfigSubscriptionLineItemPlan { /** * The replacement behavior to use for this plan. */ replacementBehavior?: BillingReplacementBehavior; /** * How many trial days to give before charging for this plan. */ trialDays?: number; /** * The line items for this plan. */ lineItems: (BillingConfigRecurringLineItem | BillingConfigUsageLineItem)[]; } ``` ### BillingConfigRecurringLineItem * amount The amount to charge for this line item. ```ts number ``` * currencyCode The currency code for this line item. ```ts string ``` * discount An optional discount to apply for this line item. ```ts BillingConfigSubscriptionPlanDiscount ``` * interval The recurring interval for this line item. Must be either \`Every30Days\` or \`Annual\`. ```ts BillingInterval.Every30Days | BillingInterval.Annual ``` ```ts export interface BillingConfigRecurringLineItem extends BillingConfigLineItem { /** * The recurring interval for this line item. * * Must be either `Every30Days` or `Annual`. */ interval: BillingInterval.Every30Days | BillingInterval.Annual; /** * An optional discount to apply for this line item. */ discount?: BillingConfigSubscriptionPlanDiscount; } ``` ### BillingConfigSubscriptionPlanDiscount * durationLimitInIntervals The number of intervals to apply the discount for. ```ts number ``` * value The discount to apply. ```ts BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage ``` ```ts export interface BillingConfigSubscriptionPlanDiscount { /** * The number of intervals to apply the discount for. */ durationLimitInIntervals?: number; /** * The discount to apply. */ value: BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage; } ``` ### BillingConfigSubscriptionPlanDiscountAmount * amount The amount to discount. Cannot be set if \`percentage\` is set. ```ts number ``` * percentage The percentage to discount. Cannot be set if \`amount\` is set. ```ts never ``` ```ts export interface BillingConfigSubscriptionPlanDiscountAmount { /** * The amount to discount. * * Cannot be set if `percentage` is set. */ amount: number; /** * The percentage to discount. * * Cannot be set if `amount` is set. */ percentage?: never; } ``` ### BillingConfigSubscriptionPlanDiscountPercentage * amount The amount to discount. Cannot be set if \`percentage\` is set. ```ts never ``` * percentage The percentage to discount. Cannot be set if \`amount\` is set. ```ts number ``` ```ts export interface BillingConfigSubscriptionPlanDiscountPercentage { /** * The amount to discount. * * Cannot be set if `percentage` is set. */ amount?: never; /** * The percentage to discount. * * Cannot be set if `amount` is set. */ percentage: number; } ``` ### BillingConfigUsageLineItem * amount The capped amount or the maximum amount to be charged in the interval. ```ts number ``` * currencyCode The currency code for this line item. ```ts string ``` * interval The usage interval for this line item. Must be set to \`Usage\`. ```ts BillingInterval.Usage ``` * terms Usage terms for this line item. ```ts string ``` ```ts export interface BillingConfigUsageLineItem extends BillingConfigLineItem { /** * The usage interval for this line item. * * Must be set to `Usage`. */ interval: BillingInterval.Usage; /** * The capped amount or the maximum amount to be charged in the interval. */ amount: number; /** * Usage terms for this line item. */ terms: string; } ``` ### BillingReplacementBehavior * ApplyImmediately ```ts APPLY_IMMEDIATELY ``` * ApplyOnNextBillingCycle ```ts APPLY_ON_NEXT_BILLING_CYCLE ``` * Standard ```ts STANDARD ``` ```ts export declare enum BillingReplacementBehavior { ApplyImmediately = "APPLY_IMMEDIATELY", ApplyOnNextBillingCycle = "APPLY_ON_NEXT_BILLING_CYCLE", Standard = "STANDARD" } ``` ### HooksConfig * afterAuth A function to call after a merchant installs your app ```ts (options: AfterAuthOptions) => void | Promise ``` ````ts interface HooksConfig { /** * A function to call after a merchant installs your app * * @param context - An object with context about the request that triggered the hook. * @param context.session - The session of the merchant that installed your app. This is the output of sessionStorage.loadSession in case people want to load their own. * @param context.admin - An object with access to the Shopify Admin API's. * * @example * Seeding data when a merchant installs your app. * ```ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { seedStoreData } from "~/db/seeds" * * const shopify = shopifyApp({ * hooks: { * afterAuth: async ({ session }) => { * seedStoreData({session}) * } * }, * // ...etc * }); * ``` */ afterAuth?: (options: AfterAuthOptions) => void | Promise; } ```` ### AfterAuthOptions * admin ```ts AdminApiContext ``` * session ```ts Session ``` ```ts export interface AfterAuthOptions { session: Session; admin: AdminApiContext; } ``` ### LogSeverity * Error ```ts 0 ``` * Warning ```ts 1 ``` * Info ```ts 2 ``` * Debug ```ts 3 ``` ```ts export declare enum LogSeverity { Error = 0, Warning = 1, Info = 2, Debug = 3 } ``` ### WebhookConfig ```ts Record ``` ## Future flags Set future flags using the `future` configuration field to opt in to upcoming breaking changes. With this feature, you can prepare for major releases ahead of time, as well as try out new features before they are released. * unstable\_newEmbeddedAuthStrategy boolean Default: false When enabled, embedded apps will fetch access tokens via [token exchange](https://shopify.dev/docs/apps/auth/get-access-tokens/token-exchange). This assumes the app has scopes declared for [Shopify managing installation](https://shopify.dev/docs/apps/auth/installation#shopify-managed-installation). Learn more about this [new embedded app auth strategy](https://shopify.dev/docs/api/shopify-app-remix#embedded-auth-strategy). ### Examples * #### The minimum viable configuration ##### /shopify.server.ts ```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ apiKey: process.env.SHOPIFY_API_KEY!, apiSecretKey: process.env.SHOPIFY_API_SECRET!, scopes: process.env.SCOPES?.split(",")!, appUrl: process.env.SHOPIFY_APP_URL!, }); export default shopify; ``` ## Examples ### addDocumentResponseHeaders Return headers on all requests Add headers to all HTML requests by calling `shopify.addDocumentResponseHeaders` in `entry.server.tsx`. ### Examples * #### Return headers on all requests ##### Description Add headers to all HTML requests by calling \`shopify.addDocumentResponseHeaders\` in \`entry.server.tsx\`. ##### \~/shopify.server.ts ```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; ``` ##### entry.server.tsx ```typescript import { addDocumentResponseHeaders } from "~/shopify.server"; export default function handleRequest( request: Request, responseStatusCode: number, responseHeaders: Headers, remixContext: EntryContext ) { const markup = renderToString( ); responseHeaders.set("Content-Type", "text/html"); addDocumentResponseHeaders(request, responseHeaders); return new Response("" + markup, { status: responseStatusCode, headers: responseHeaders, }); } ``` ### authenticate Authenticate Shopify requests Use the functions in `authenticate` to validate requests coming from Shopify. ### Examples * #### Authenticate Shopify requests ##### Description Use the functions in \`authenticate\` to validate requests coming from Shopify. ##### /app/shopify.server.ts ```typescript import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ##### /app/routes/\*\*\\/\*.jsx ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); const response = admin.graphql(`{ shop { name } }`) return json(await response.json()); } ``` ### registerWebhooks Registering shop-specific webhooks after install Trigger the registration to create the shop-specific webhook subscriptions after a merchant installs your app using the `afterAuth` hook. Learn more about [subscribing to webhooks.](https://shopify.dev/docs/api/shopify-app-remix/v3/guide-webhooks) ### Examples * #### Registering shop-specific webhooks after install ##### Description Trigger the registration to create the shop-specific webhook subscriptions after a merchant installs your app using the \`afterAuth\` hook. Learn more about \[subscribing to webhooks.]\(https\://shopify.dev/docs/api/shopify-app-remix/v3/guide-webhooks) ##### app/shopify.server.ts ```typescript import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ webhooks: { PRODUCTS_CREATE: { deliveryMethod: DeliveryMethod.Http, callbackUrl: "/webhooks/products/create", }, }, hooks: { afterAuth: async ({ session }) => { // Register webhooks for the shop // In this example, every shop will have these webhooks // You could wrap this in some custom shop specific conditional logic if needed shopify.registerWebhooks({ session }); }, }, // ...etc }); ``` ### sessionStorage Storing sessions with Prisma Import the `@shopify/shopify-app-session-storage-prisma` package to store sessions in your Prisma database. ### Examples * #### Storing sessions with Prisma ##### Description Import the \`@shopify/shopify-app-session-storage-prisma\` package to store sessions in your Prisma database. ##### /app/shopify.server.ts ```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; import prisma from "~/db.server"; const shopify = shopifyApp({ sessionStorage: new PrismaSessionStorage(prisma), // ...etc }) // shopify.sessionStorage is an instance of PrismaSessionStorage ``` ### unauthenticated Using unauthenticated contexts Create contexts for requests that don't come from Shopify. ### Examples * #### Using unauthenticated contexts ##### Description Create contexts for requests that don't come from Shopify. ##### /app/shopify.server.ts ```typescript import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ##### /app/routes/\*\*\\/\*.jsx ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import { authenticateExternal } from "~/helpers/authenticate" import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const shop = await authenticateExternal(request) const {admin} = await shopify.unauthenticated.admin(shop); const response = admin.graphql(`{ shop { currencyCode } }`) return json(await response.json()); } ``` ### login Creating a login page Use `shopify.login` to create a login form, in a route that can handle GET and POST requests. ### Examples * #### Creating a login page ##### Description Use \`shopify.login\` to create a login form, in a route that can handle GET and POST requests. ##### /app/shopify.server.ts ```typescript import { ApiVersion, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ##### /app/routes/auth/login.tsx ```typescript import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const errors = shopify.login(request); return json(errors); } export async function action({ request }: ActionFunctionArgs) { const errors = shopify.login(request); return json(errors); } export default function Auth() { const actionData = useActionData(); const [shop, setShop] = useState(""); return (
Login
); } ``` ## Related [![](https://shopify.dev/images/icons/32/pickaxe-1.png)![](https://shopify.dev/images/icons/32/pickaxe-1-dark.png)](https://shopify.dev/docs/api/shopify-app-remix/authenticate) [Authenticate requests coming from Shopify.Authenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/authenticate) [![](https://shopify.dev/images/icons/32/pickaxe-1.png)![](https://shopify.dev/images/icons/32/pickaxe-1-dark.png)](https://shopify.dev/docs/api/shopify-app-remix/unauthenticated) [Interact with the API on non-Shopify requests.Unauthenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/unauthenticated)