--- 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: v1 api_name: shopify-app-remix source_url: html: 'https://shopify.dev/docs/api/shopify-app-remix/v1/entrypoints/shopifyapp' md: 'https://shopify.dev/docs/api/shopify-app-remix/v1/entrypoints/shopifyapp.md' --- # shopify​App 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 Config extends AppConfigArg\ 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. ### AppConfigArg * 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 ``` * sessionStorage An adaptor for storing sessions in your database of choice. Shopify provides multiple session storage adaptors and you can create your own. ```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 ``` * webhooks The config for the webhook topics your app would like to subscribe to. This can be in used in conjunction with the afterAuth hook to register webhook topics when a user installs your app. Or you can use this function in other processes such as background jobs. ```ts WebhookConfig ``` * 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 ``` * distribution How your app is distributed. Default is \`AppDistribution.AppStore\`. ```ts AppDistribution ``` * apiVersion What version of Shopify's Admin API's would you like to use. ```ts ApiVersion ``` * 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 ``` * apiKey ```ts string ``` * apiSecretKey ```ts string ``` * scopes ```ts string[] | AuthScopes ``` * adminApiAccessToken ```ts string ``` * userAgentPrefix ```ts string ``` * privateAppStorefrontAccessToken ```ts string ``` * customShopDomains ```ts (string | RegExp)[] ``` * billing ```ts BillingConfig ``` * restResources ```ts T ``` * logger ```ts { log?: LogFunction; level?: LogSeverity; httpRequests?: boolean; timestamps?: boolean; } ``` ````ts export interface AppConfigArg< Resources extends ShopifyRestResources = ShopifyRestResources, Storage extends SessionStorage = SessionStorage, > extends Omit< ApiConfigArg, | 'hostName' | 'hostScheme' | 'isEmbeddedApp' | 'apiVersion' | 'isCustomStoreApp' > { /** * 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. * * {@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 webhook topics your app would like to subscribe to. * * {@link https://shopify.dev/docs/apps/webhooks} * * This can be in used in conjunction with the afterAuth hook to register webhook topics when a user installs your app. Or you can use this function in other processes such as background jobs. * * @example * Registering for a webhook when a merchant uninstalls your app. * ```ts * // /app/shopify.server.ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * webhooks: { * APP_UNINSTALLED: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks", * }, * }, * hooks: { * afterAuth: async ({ session }) => { * shopify.registerWebhooks({ session }); * } * }, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * * // /app/routes/webhooks.jsx * import { ActionArgs } from "@remix-run/node"; * * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionArgs) => { * const { topic, shop } = await authenticate.webhook(request); * * switch (topic) { * case "APP_UNINSTALLED": * await db.session.deleteMany({ where: { shop } }); * break; * case "CUSTOMERS_DATA_REQUEST": * case "CUSTOMERS_REDACT": * case "SHOP_REDACT": * default: * throw new Response("Unhandled webhook topic", { status: 404 }); * } * 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`. * * {@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/} * * @defaultValue `LATEST_API_VERSION` from `@shopify/shopify-app-remix` * * @example * Using the latest API Version (Recommended) * ```ts * import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * apiVersion: LATEST_API_VERSION, * }); * ``` */ 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 the latest API Version (Recommended) * ```ts * // /app/shopify.server.ts * import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ...etc * apiVersion: LATEST_API_VERSION, * }); * export default shopify; * export const authenticate = shopify.authenticate; * * // /app/routes/auth/$.jsx * import { LoaderArgs } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * await authenticate.admin(request); * * return null * } * ``` */ authPathPrefix?: string; } ```` ### WebhookConfig * \[key: string] ```ts WebhookHandler | WebhookHandler[] ``` ```ts export interface WebhookConfig { [key: string]: WebhookHandler | WebhookHandler[]; } ``` ### 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 * Registering webhooks and 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 }) => { * shopify.registerWebhooks({ session }); * seedStoreData({session}) * } * }, * webhooks: { * APP_UNINSTALLED: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks", * }, * }, * // ...etc * }); * ``` */ afterAuth?: (options: AfterAuthOptions) => void | Promise; } ```` ### AfterAuthOptions * session ```ts Session ``` * admin ```ts AdminApiContext ``` ```ts export interface AfterAuthOptions< R extends ShopifyRestResources = ShopifyRestResources, > { session: Session; admin: AdminApiContext; } ``` ### AdminApiContext * rest Methods for interacting with the Shopify Admin REST API There are methods for interacting with individual REST resources. You can also make \`GET\`, \`POST\`, \`PUT\` and \`DELETE\` requests should the REST resources not meet your needs. ```ts RestClientWithResources ``` * graphql Methods for interacting with the Shopify Admin GraphQL API ```ts GraphQLClient ``` ````ts export interface AdminApiContext< Resources extends ShopifyRestResources = ShopifyRestResources, > { /** * Methods for interacting with the Shopify Admin REST API * * There are methods for interacting with individual REST resources. You can also make `GET`, `POST`, `PUT` and `DELETE` requests should the REST resources not meet your needs. * * {@link https://shopify.dev/docs/api/admin-rest} * * @example * Using REST resources. * Getting the number of orders in a store using REST resources. * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-07"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * ```ts * // /app/routes/**\/*.ts * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { admin, session } = await authenticate.admin(request); * return json(admin.rest.resources.Order.count({ session })); * }; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.` to make custom requests to the API. * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * ```ts * // /app/routes/**\/*.ts * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { admin, session } = await authenticate.admin(request); * const response = await admin.rest.get({ path: "/customers/count.json" }); * const customers = await response.json(); * return json({ customers }); * }; * ``` */ rest: RestClientWithResources; /** * Methods for interacting with the Shopify Admin GraphQL API * * {@link https://shopify.dev/docs/api/admin-graphql} * {@link https://github.com/Shopify/shopify-api-js/blob/main/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * import { ActionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionArgs) { * 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({ data: productData.data }); * } * ``` */ graphql: GraphQLClient; } ```` ### RestClientWithResources ```ts RemixRestClient & {resources: Resources} ``` ### 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', } ``` ### 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 ? SingleMerchantApp : Config['distribution'] extends AppDistribution.AppStore ? AppStoreApp : AppStoreApp ``` ### AdminApp * sessionStorage The \`SessionStorage\` instance you passed in as a config option. ```ts SessionStorageType ``` * addDocumentResponseHeaders Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ```ts AddDocumentResponseHeaders ``` * registerWebhooks Register webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ```ts RegisterWebhooks ``` * authenticate Ways to authenticate requests from different surfaces across Shopify. ```ts Authenticate ``` * unauthenticated Ways to get Contexts from requests that do not originate from Shopify. ```ts Unauthenticated> ``` ```ts ShopifyAppBase ``` ### SessionStorageType ```ts Config['sessionStorage'] extends SessionStorage ? Config['sessionStorage'] : SessionStorage ``` ### AddDocumentResponseHeaders * request ```ts Request ``` * headers ```ts Headers ``` void ```ts void ``` ```ts type AddDocumentResponseHeaders = (request: Request, headers: Headers) => void; ``` ### RegisterWebhooks * options ```ts RegisterWebhooksOptions ``` Promise\ ```ts Promise ``` ```ts type RegisterWebhooks = ( 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; } ``` ### 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> ``` * 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< RestResourcesType, keyof Config['webhooks'] | MandatoryTopics > ``` ````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/shopify.server.ts * import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` */ admin: AuthenticateAdmin>; /** * 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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderArgs) { * 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/shopify.server.ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * webhooks: { * APP_UNINSTALLED: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks", * }, * }, * hooks: { * afterAuth: async ({ session }) => { * shopify.registerWebhooks({ session }); * }, * }, * // ...etc * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * ```ts * // /app/routes/webhooks.ts * import { ActionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionArgs) => { * const { topic, shop, session } = await authenticate.webhook(request); * * switch (topic) { * case "APP_UNINSTALLED": * if (session) { * await db.session.deleteMany({ where: { shop } }); * } * break; * case "CUSTOMERS_DATA_REQUEST": * case "CUSTOMERS_REDACT": * case "SHOP_REDACT": * default: * throw new Response("Unhandled webhook topic", { status: 404 }); * } * * throw new Response(); * }; * ``` */ webhook: AuthenticateWebhook< RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } ```` ### AuthenticateAdmin * request ```ts Request ``` Promise\> ```ts Promise> ``` ```ts type AuthenticateAdmin< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; ``` ### AdminContext ```ts Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext : EmbeddedAdminContext ``` ### NonEmbeddedAdminContext * 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 ``` * admin Methods for interacting with the GraphQL / REST Admin APIs 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 ``` ```ts export interface NonEmbeddedAdminContext< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > extends AdminContextInternal {} ``` ### BillingContext * require Checks if the shop has an active payment for any plan defined in the \`billing\` config option. ```ts (options: RequireBillingOptions) => Promise ``` * request Requests payment for the plan. ```ts (options: RequestBillingOptions) => Promise ``` * cancel Cancels an ongoing subscription, given its ID. ```ts (options: CancelBillingOptions) => 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 request payment. * ```ts * // /app/routes/**\/*.ts * import { LoaderArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Using a plan selection page. * Redirect to a different page in the `onFailure` callback, where the merchant can select a billing plan. * ```ts * // /app/routes/**\/*.ts * import { LoaderArgs, redirect } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN, ANNUAL_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ require: ( options: RequireBillingOptions, ) => 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 { LoaderArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ * plan: MONTHLY_PLAN, * isTest: true, * returnUrl: '/billing-complete', * }), * }); * * // 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]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * 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 { LoaderArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ cancel: (options: CancelBillingOptions) => Promise; } ```` ### RequireBillingOptions * plans The plans to check for. Must be one of the values defined in the \`billing\` config option. ```ts (keyof Config["billing"])[] ``` * onFailure How to handle the request if the shop doesn't have an active payment for any plan. ```ts (error: any) => Promise ``` * isTest ```ts boolean ``` ```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; } ``` ### RequestBillingOptions * plan The plan to request. Must be one of the values defined in the \`billing\` config option. ```ts keyof Config["billing"] ``` ```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']; } ``` ### CancelBillingOptions * subscriptionId The ID of the subscription to cancel. ```ts string ``` * prorate Whether to prorate the cancellation. ```ts boolean ``` * isTest ```ts boolean ``` ```ts export interface CancelBillingOptions { /** * The ID of the subscription to cancel. */ subscriptionId: string; /** * Whether to prorate the cancellation. * * {@link https://shopify.dev/docs/apps/billing/subscriptions/cancel-recurring-charges} */ prorate?: boolean; isTest?: boolean; } ``` ### EmbeddedAdminContext * sessionToken The decoded and validated session token for the request. Returned only if \`isEmbeddedApp\` is \`true\`. ```ts JwtPayload ``` * 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 ``` * admin Methods for interacting with the GraphQL / REST Admin APIs 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 ``` ````ts export interface EmbeddedAdminContext< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > 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 * // 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; * ``` * ```ts * // /app/routes/**\/*.ts * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { sessionToken } = await authenticate.public.checkout( * request * ); * return json(await getMyAppData({user: sessionToken.sub})); * }; * ``` */ 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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { session, redirect } = await authenticate.admin(request); * return redirect("/"); * }; * ``` * * @example * Redirecting outside of Shopify admin. * Pass in a `target` option of `_top` or `_parent` to go to an external URL. * ```ts * // /app/routes/admin/my-route.ts * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * const { session, redirect } = await authenticate.admin(request); * return redirect("/", { target: '_parent' }); * }; * ``` */ redirect: RedirectFunction; } ```` ### RedirectFunction * url ```ts string ``` * init ```ts RedirectInit ``` TypedResponse\ ```ts TypedResponse ``` ```ts export type RedirectFunction = ( url: string, init?: RedirectInit, ) => TypedResponse; ``` ### RedirectInit ```ts number | (ResponseInit & {target?: RedirectTarget}) ``` ### RedirectTarget ```ts '_self' | '_parent' | '_top' ``` ### RestResourcesType ```ts Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources ``` ### AuthenticatePublic Methods for authenticating Requests from Shopify's public surfaces To maintain backwards compatability this is a function and an object. Do not use \`authenticate.public()\`. Use \`authenticate.public.checkout()\` instead. \`authenticate.public()\` will be removed in v2. Methods are: - \`authenticate.public.checkout()\` for authenticating requests from checkout extensions - \`authenticate.public.appProxy()\` for authenticating requests from app proxies ```ts AuthenticateCheckout & AuthenticatePublicObject ``` ### AuthenticateCheckout * request ```ts Request ``` * options ```ts AuthenticateCheckoutOptions ``` Promise\ ```ts Promise ``` ```ts export type AuthenticateCheckout = ( request: Request, options?: AuthenticateCheckoutOptions, ) => Promise; ``` ### AuthenticateCheckoutOptions * corsHeaders ```ts string[] ``` ```ts export interface AuthenticateCheckoutOptions { corsHeaders?: string[]; } ``` ### CheckoutContext Authenticated Context for a checkout request * 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 ``` * cors A function that ensures the CORS headers are set correctly for the response. ```ts EnsureCORSFunction ``` ````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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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; } ```` ### AuthenticatePublicObject * checkout Authenticate a request from a checkout extension ```ts AuthenticateCheckout ``` * appProxy Authenticate a request from an app proxy ```ts AuthenticateAppProxy ``` ````ts interface AuthenticatePublicObject { /** * Authenticate a request from a checkout extension * * @example * Authenticating a checkout extension request * ```ts * // /app/routes/public/widgets.ts * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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; } ```` ### AuthenticateAppProxy * request ```ts Request ``` Promise\ ```ts Promise ``` ```ts export type AuthenticateAppProxy = ( request: Request, ) => Promise; ``` ### AppProxyContext * 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 ``` * admin No session is available for the shop that made this request. Therefore no methods for interacting with the GraphQL / REST Admin APIs are available. ```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 ``` * liquid A utility for creating a Liquid Response. ```ts LiquidResponseFunction ``` ```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 / REST Admin APIs 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 export type LiquidResponseFunction = ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response; ``` ### Options * layout ```ts boolean ``` ```ts interface Options { layout?: boolean; } ``` ### AppProxyContextWithSession * 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 ``` * admin Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request. ```ts AdminApiContext ``` * storefront Method for interacting with the Shopify Storefront Graphql API for the store that made the request. ```ts StorefrontContext ``` * liquid A utility for creating a Liquid Response. ```ts LiquidResponseFunction ``` ````ts export interface AppProxyContextWithSession< Resources extends ShopifyRestResources = ShopifyRestResources, > 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 your app's data using an offline session for the shop that made the request. * ```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 }) => { * const { session } = await authenticate.public.appProxy(request); * return json(await getMyAppModelData({shop: session.shop)); * }; * ``` */ session: Session; /** * Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request. * * @example * Interacting with the Admin API. * Use the `admin` object to interact with the REST or GraphQL APIs. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionArgs) { * 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 }: ActionArgs) { * const { admin } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql(`{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 * import { ActionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionArgs) { * const { storefront } = await authenticate.storefront(request); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` */ graphql: GraphQLClient; } ```` ### AuthenticateWebhook * request ```ts Request ``` Promise< WebhookContext\ | WebhookContextWithSession\ > ```ts Promise< WebhookContext | WebhookContextWithSession > ``` ```ts export type AuthenticateWebhook< Resources extends ShopifyRestResources = ShopifyRestResources, Topics = string | number | symbol, > = ( request: Request, ) => Promise< WebhookContext | WebhookContextWithSession >; ``` ### WebhookContext * session ```ts undefined ``` * admin ```ts undefined ``` * apiVersion The API version used for the webhook. ```ts string ``` * shop The shop where the webhook was triggered. ```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 ``` * payload The payload from the webhook request. ```ts JSONValue ``` ```ts export interface WebhookContext extends Context { session: undefined; admin: undefined; } ``` ### JSONValue ```ts string | number | boolean | null | JSONObject | JSONArray ``` ### JSONObject * \[x: string] ```ts JSONValue ``` ```ts interface JSONObject { [x: string]: JSONValue; } ``` ### JSONArray * length Gets or sets the length of the array. This is a number one higher than the highest index in the array. ```ts number ``` * toString Returns a string representation of an array. ```ts () => string ``` * toLocaleString Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. ```ts () => string ``` * pop Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified. ```ts () => JSONValue ``` * push Appends new elements to the end of an array, and returns the new length of the array. ```ts (...items: JSONValue[]) => number ``` * concat Combines two or more arrays. This method returns a new array without modifying any existing arrays. ```ts { (...items: ConcatArray[]): JSONValue[]; (...items: (JSONValue | ConcatArray)[]): JSONValue[]; } ``` * join Adds all the elements of an array into a string, separated by the specified separator string. ```ts (separator?: string) => string ``` * reverse Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array. ```ts () => JSONValue[] ``` * shift Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified. ```ts () => JSONValue ``` * slice Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array. ```ts (start?: number, end?: number) => JSONValue[] ``` * sort Sorts an array in place. This method mutates the array and returns a reference to the same array. ```ts (compareFn?: (a: JSONValue, b: JSONValue) => number) => JSONArray ``` * splice Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. ```ts { (start: number, deleteCount?: number): JSONValue[]; (start: number, deleteCount: number, ...items: JSONValue[]): JSONValue[]; } ``` * unshift Inserts new elements at the start of an array, and returns the new length of the array. ```ts (...items: JSONValue[]) => number ``` * indexOf Returns the index of the first occurrence of a value in an array, or -1 if it is not present. ```ts (searchElement: JSONValue, fromIndex?: number) => number ``` * lastIndexOf Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present. ```ts (searchElement: JSONValue, fromIndex?: number) => number ``` * every Determines whether all the members of an array satisfy the specified test. ```ts { (predicate: (value: JSONValue, index: number, array: JSONValue[]) => value is S, thisArg?: any): this is S[]; (predicate: (value: JSONValue, index: number, array: JSONValue[]) => unknown, thisArg?: any): boolean; } ``` * some Determines whether the specified callback function returns true for any element of an array. ```ts (predicate: (value: JSONValue, index: number, array: JSONValue[]) => unknown, thisArg?: any) => boolean ``` * forEach Performs the specified action for each element in an array. ```ts (callbackfn: (value: JSONValue, index: number, array: JSONValue[]) => void, thisArg?: any) => void ``` * map Calls a defined callback function on each element of an array, and returns an array that contains the results. ```ts (callbackfn: (value: JSONValue, index: number, array: JSONValue[]) => U, thisArg?: any) => U[] ``` * filter Returns the elements of an array that meet the condition specified in a callback function. ```ts { (predicate: (value: JSONValue, index: number, array: JSONValue[]) => value is S, thisArg?: any): S[]; (predicate: (value: JSONValue, index: number, array: JSONValue[]) => unknown, thisArg?: any): JSONValue[]; } ``` * reduce Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ```ts { (callbackfn: (previousValue: JSONValue, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => JSONValue): JSONValue; (callbackfn: (previousValue: JSONValue, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => JSONValue, initialValue: JSONValue): JSONValue; (callbackfn: (previousValue: U, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => U, initialValue: U): U; } ``` * reduceRight Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. ```ts { (callbackfn: (previousValue: JSONValue, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => JSONValue): JSONValue; (callbackfn: (previousValue: JSONValue, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => JSONValue, initialValue: JSONValue): JSONValue; (callbackfn: (previousValue: U, currentValue: JSONValue, currentIndex: number, array: JSONValue[]) => U, initialValue: U): U; } ``` * find Returns the value of the first element in the array where predicate is true, and undefined otherwise. ```ts { (predicate: (this: void, value: JSONValue, index: number, obj: JSONValue[]) => value is S, thisArg?: any): S; (predicate: (value: JSONValue, index: number, obj: JSONValue[]) => unknown, thisArg?: any): JSONValue; } ``` * findIndex Returns the index of the first element in the array where predicate is true, and -1 otherwise. ```ts (predicate: (value: JSONValue, index: number, obj: JSONValue[]) => unknown, thisArg?: any) => number ``` * fill Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array ```ts (value: JSONValue, start?: number, end?: number) => JSONArray ``` * copyWithin Returns the this object after copying a section of the array identified by start and end to the same array starting at position target ```ts (target: number, start: number, end?: number) => JSONArray ``` * entries Returns an iterable of key, value pairs for every entry in the array ```ts () => IterableIterator<[number, JSONValue]> ``` * keys Returns an iterable of keys in the array ```ts () => IterableIterator ``` * values Returns an iterable of values in the array ```ts () => IterableIterator ``` * includes Determines whether an array includes a certain element, returning true or false as appropriate. ```ts (searchElement: JSONValue, fromIndex?: number) => boolean ``` * flatMap Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1. ```ts (callback: (this: This, value: JSONValue, index: number, array: JSONValue[]) => U | readonly U[], thisArg?: This) => U[] ``` * flat Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth. ```ts (this: A, depth?: D) => FlatArray[] ``` * \_\_@iterator\@526 Iterator ```ts () => IterableIterator ``` * \_\_@unscopables\@528 Returns an object whose properties have the value 'true' when they will be absent when used in a 'with' statement. ```ts () => { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; } ``` * at Takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. ```ts (index: number) => JSONValue ``` ```ts interface JSONArray extends Array {} ``` ### WebhookContextWithSession * session A session with an offline token for the shop. Returned only if there is a session for the shop. ```ts Session ``` * admin An admin context for the webhook. Returned only if there is a session for the shop. ```ts { rest: RestClient & Resources; graphql: GraphqlClient; } ``` * apiVersion The API version used for the webhook. ```ts string ``` * shop The shop where the webhook was triggered. ```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 ``` * payload The payload from the webhook request. ```ts JSONValue ``` ```ts export interface WebhookContextWithSession< Topics = string | number | symbol, Resources extends ShopifyRestResources = any, > extends Context { /** * A session with an offline token for the shop. * * Returned only if there is a session for the shop. */ session: Session; /** * An admin context for the webhook. * * Returned only if there is a session for the shop. */ admin: { /** A REST client. */ rest: InstanceType & Resources; /** A GraphQL client. */ graphql: InstanceType; }; } ``` ### MandatoryTopics ```ts 'CUSTOMERS_DATA_REQUEST' | 'CUSTOMERS_REDACT' | 'SHOP_REDACT' ``` ### 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 { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` */ 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 { LoaderArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * 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 export type GetUnauthenticatedAdminContext< Resources extends ShopifyRestResources, > = (shop: string) => Promise>; ``` ### UnauthenticatedAdminContext * 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 ``` * admin Methods for interacting with the GraphQL / REST Admin APIs for the given store. ```ts AdminApiContext ``` ````ts export interface UnauthenticatedAdminContext< Resources extends ShopifyRestResources, > { /** * 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 { LoaderArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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 / REST Admin APIs for the given store. */ admin: AdminApiContext; } ```` ### GetUnauthenticatedStorefrontContext * shop ```ts string ``` Promise\ ```ts Promise ``` ```ts export type GetUnauthenticatedStorefrontContext = ( 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 { LoaderArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderArgs) => { * 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. */ storefront: StorefrontContext; } ```` ### SingleMerchantApp ```ts ShopifyAppBase & ShopifyAppLogin ``` ### ShopifyAppBase * sessionStorage The \`SessionStorage\` instance you passed in as a config option. ```ts SessionStorageType ``` * addDocumentResponseHeaders Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ```ts AddDocumentResponseHeaders ``` * registerWebhooks Register webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ```ts RegisterWebhooks ``` * authenticate Ways to authenticate requests from different surfaces across Shopify. ```ts Authenticate ``` * 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({ * sesssionStorage: 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 webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. * * @example * Registering webhooks. * Trigger the registration after a merchant installs your app using the `afterAuth` hook. * ```ts * import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * hooks: { * afterAuth: async ({ session }) => { * shopify.registerWebhooks({ session }); * } * }, * webhooks: { * APP_UNINSTALLED: { * deliveryMethod: DeliveryMethod.Http, * callbackUrl: "/webhooks", * }, * }, * // ...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 { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderArgs, json } from "@remix-run/node"; * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` */ 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 { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; * import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * ``` * ```ts * // /app/routes/**\/*.jsx * import { LoaderArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` */ 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 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 { LATEST_API_VERSION, 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 }: LoaderArgs) { * const errors = shopify.login(request); * * return json(errors); * } * * export async function action({ request }: ActionArgs) { * 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 type Login = (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 ``` Examples ### Examples * #### The minimum viable configuration ##### Example ```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; ``` * #### 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({ sesssionStorage: new PrismaSessionStorage(prisma), // ...etc }) // shopify.sessionStorage is an instance of PrismaSessionStorage ``` * #### 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, }); } ``` * #### Registering webhooks ##### Description Trigger the registration after a merchant installs your app using the \`afterAuth\` hook. ##### Example ```typescript import { DeliveryMethod, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ hooks: { afterAuth: async ({ session }) => { shopify.registerWebhooks({ session }); } }, webhooks: { APP_UNINSTALLED: { deliveryMethod: DeliveryMethod.Http, callbackUrl: "/webhooks", }, }, // ...etc }); ``` * #### Authenticate Shopify requests ##### Description Use the functions in \`authenticate\` to validate requests coming from Shopify. ##### /app/shopify.server.ts ```typescript import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; const shopify = shopifyApp({ restResources, // ...etc }); export default shopify; ``` ##### /app/routes/\*\*\\/\*.jsx ```typescript import { LoaderArgs, json } from "@remix-run/node"; import shopify from "../../shopify.server"; export async function loader({ request }: LoaderArgs) { const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); return json(await admin.rest.resources.Product.count({ session })); } ``` * #### Using unauthenticated contexts ##### Description Create contexts for requests that don't come from Shopify. ##### /app/shopify.server.ts ```typescript import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; import { restResources } from "@shopify/shopify-api/rest/admin/2023-04"; const shopify = shopifyApp({ restResources, // ...etc }); export default shopify; ``` ##### /app/routes/\*\*\\/\*.jsx ```typescript import { LoaderArgs, json } from "@remix-run/node"; import { authenticateExternal } from "~/helpers/authenticate" import shopify from "../../shopify.server"; export async function loader({ request }: LoaderArgs) { const shop = await authenticateExternal(request) const {admin} = await shopify.unauthenticated.admin(shop); return json(await admin.rest.resources.Product.count({ session })); } ``` * #### 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 { LATEST_API_VERSION, 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 }: LoaderArgs) { const errors = shopify.login(request); return json(errors); } export async function action({ request }: ActionArgs) { const errors = shopify.login(request); return json(errors); } export default function Auth() { const actionData = useActionData(); const [shop, setShop] = useState(""); return (
Login
); } ``` ## Related [Authenticate requests coming from Shopify. - Authenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/authenticate) [Interact with the API on non-Shopify requests. - Unauthenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/unauthenticated)