--- 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. 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' --- # shopifyApp 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)**​) Creates an object your app will use to interact with Shopify. ### 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 * \_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\`. ```ts AppDistribution ``` * future Future flags to include for this app. ```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. ```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 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 ``` ### AppDistribution * AppStore ```ts app_store ``` * SingleMerchant ```ts single_merchant ``` * ShopifyAdmin ```ts shopify_admin ``` ### HooksConfig * afterAuth A function to call after a merchant installs your app ```ts (options: AfterAuthOptions) => void | Promise ``` ### AfterAuthOptions * admin ```ts AdminApiContext ``` * session ```ts Session ``` ### AdminApiContext Provides utilities that apps can use to make requests to the Admin API. * graphql Methods for interacting with the Shopify Admin GraphQL API ```ts GraphQLClient ``` * 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 ``` ### GraphQLClient * query ```ts string ``` * options ```ts GraphQLQueryOptions ``` returns ```ts Promise ``` ### GraphQLQueryOptions * apiVersion ```ts ApiVersion ``` * headers ```ts { [key: string]: any; } ``` * tries ```ts number ``` * variables ```ts QueryVariables ``` ### QueryVariables * \[key: string] ```ts any ``` ### RestClientWithResources ```ts RemixRestClient & {resources: Resources} ``` ### RemixRestClient * session ```ts Session ``` * get Performs a GET request on the given path. ```ts (params: GetRequestParams) => Promise ``` * post Performs a POST request on the given path. ```ts (params: PostRequestParams) => Promise ``` * put Performs a PUT request on the given path. ```ts (params: PostRequestParams) => Promise ``` * delete Performs a DELETE request on the given path. ```ts (params: GetRequestParams) => Promise ``` ### WebhookConfig * \[key: string] ```ts WebhookHandler | WebhookHandler[] ``` ### 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 * 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 webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ```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> ``` ### AddDocumentResponseHeaders * request ```ts Request ``` * headers ```ts Headers ``` returns ```ts 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> ``` * 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 > ``` ### AuthenticateAdmin Authenticates requests coming from the Shopify admin. The shape of the returned object changes depending on the \`isEmbeddedApp\` config. * request ```ts Request ``` returns ```ts Promise> ``` ### AdminContext ```ts Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext : EmbeddedAdminContext ``` ### NonEmbeddedAdminContext * 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 ``` * 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 ``` ### BillingContext Provides utilities that apps can use to request billing for the app using the Admin API. * cancel Cancels an ongoing subscription, given its ID. ```ts (options: CancelBillingOptions) => 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 ``` ### CancelBillingOptions * isTest ```ts boolean ``` * prorate Whether to prorate the cancellation. ```ts boolean ``` * subscriptionId The ID of the subscription to cancel. ```ts string ``` ### RequestBillingOptions * 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 ``` * isTest Whether this is a test purchase. ```ts boolean ``` * lineItems The line items for this plan. ```ts ({ interval?: BillingInterval.Every30Days | BillingInterval.Annual; discount?: { durationLimitInIntervals?: number; value?: { amount?: number; percentage?: never; } | { amount?: never; percentage?: number; }; }; amount?: number; currencyCode?: string; } | { interval?: BillingInterval.Usage; amount?: number; terms?: string; currencyCode?: string; })[] ``` * plan The plan to request. Must be one of the values defined in the \`billing\` config option. ```ts keyof Config["billing"] ``` * replacementBehavior The replacement behavior to use for this plan. ```ts BillingReplacementBehavior ``` * returnUrl Override the return URL after the purchase is complete. ```ts string ``` * trialDays How many trial days to give before charging for this plan. ```ts number ``` ### 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"])[] ``` ### EnsureCORSFunction ### EmbeddedAdminContext * 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 ``` * 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 ``` ### RedirectFunction * url ```ts string ``` * init ```ts RedirectInit ``` returns ```ts 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 Authenticates requests coming from Shopify checkout extensions. * request ```ts Request ``` * options ```ts AuthenticateCheckoutOptions ``` returns ```ts Promise ``` ### AuthenticateCheckoutOptions * corsHeaders ```ts 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 ``` ### AuthenticatePublicObject * appProxy Authenticate a request from an app proxy ```ts AuthenticateAppProxy ``` * checkout Authenticate a request from a checkout extension ```ts AuthenticateCheckout ``` ### AuthenticateAppProxy Authenticates requests coming to the app from Shopify app proxies. * request ```ts Request ``` returns ```ts Promise ``` ### AppProxyContext * 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 ``` * 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 ``` ### LiquidResponseFunction * body ```ts string ``` * initAndOptions ```ts number | (ResponseInit & Options) ``` returns ```ts Response ``` ### Options * layout ```ts boolean ``` ### AppProxyContextWithSession * admin Methods for interacting with the GraphQL / REST Admin APIs 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 ``` ### StorefrontContext Provides utilities that apps can use to make requests to the Storefront API. * 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 ``` ### AuthenticateWebhook Verifies requests coming from Shopify webhooks. * request ```ts Request ``` returns ```ts Promise< WebhookContext | WebhookContextWithSession > ``` ### WebhookContext * admin ```ts undefined ``` * apiVersion The API version used for the webhook. ```ts string ``` * payload The payload from the webhook request. ```ts JSONValue ``` * session ```ts undefined ``` * 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 ``` ### JSONValue ```ts string | number | boolean | null | JSONObject | JSONArray ``` ### JSONObject * \[x: string] ```ts JSONValue ``` ### JSONArray * \_\_@iterator\@410 Iterator ```ts () => IterableIterator ``` * \_\_@unscopables\@412 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 ```ts (index: number) => JSONValue ``` * 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[]; } ``` * 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]> ``` * 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; } ``` * 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 ``` * 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[]; } ``` * 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 ``` * 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[] ``` * 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[] ``` * forEach Performs the specified action for each element in an array. ```ts (callbackfn: (value: JSONValue, index: number, array: JSONValue[]) => void, thisArg?: any) => void ``` * includes Determines whether an array includes a certain element, returning true or false as appropriate. ```ts (searchElement: JSONValue, fromIndex?: number) => boolean ``` * 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 ``` * join Adds all the elements of an array into a string, separated by the specified separator string. ```ts (separator?: string) => string ``` * keys Returns an iterable of keys in the array ```ts () => IterableIterator ``` * 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 ``` * length Gets or sets the length of the array. This is a number one higher than the highest index in the array. ```ts number ``` * 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[] ``` * 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 ``` * 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; } ``` * 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[] ``` * 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 ``` * 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[]; } ``` * toLocaleString Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. ```ts () => string ``` * toString Returns a string representation of an array. ```ts () => string ``` * unshift Inserts new elements at the start of an array, and returns the new length of the array. ```ts (...items: JSONValue[]) => number ``` * values Returns an iterable of values in the array ```ts () => IterableIterator ``` ### WebhookContextWithSession * 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 ``` * payload The payload from the webhook request. ```ts JSONValue ``` * session A session with an offline token for the shop. Returned only if there is a session for the shop. ```ts Session ``` * 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 ``` ### MandatoryTopics ```ts 'CUSTOMERS_DATA_REQUEST' | 'CUSTOMERS_REDACT' | 'SHOP_REDACT' ``` ### RegisterWebhooks * options ```ts RegisterWebhooksOptions ``` returns ```ts Promise ``` ### RegisterWebhooksOptions * session The Shopify session used to register webhooks using the Admin API. ```ts 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 ``` ### GetUnauthenticatedAdminContext Creates an unauthenticated Admin context. * shop ```ts string ``` returns ```ts Promise> ``` ### UnauthenticatedAdminContext * admin Methods for interacting with the GraphQL / REST Admin APIs 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 ``` ### GetUnauthenticatedStorefrontContext Creates an unauthenticated Storefront context. * shop ```ts string ``` returns ```ts 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 ``` ### 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 webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ```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> ``` ### 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 ``` ### Login * request ```ts Request ``` returns ```ts Promise ``` ### LoginError * shop ```ts LoginErrorType ``` ### LoginErrorType * MissingShop ```ts MISSING_SHOP ``` * InvalidShop ```ts INVALID_SHOP ``` ### AppStoreApp ```ts ShopifyAppBase & ShopifyAppLogin ``` Examples ### Examples * #### ##### Example ```ts 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; ``` * #### Return headers on all requests ##### Description Add headers to all HTML requests by calling \`shopify.addDocumentResponseHeaders\` in \`entry.server.tsx\`. ##### \~/shopify.server.ts ```ts import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; ``` ##### entry.server.tsx ```ts 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 Shopify requests ##### Description Use the functions in \`authenticate\` to validate requests coming from Shopify. ##### /app/shopify.server.ts ```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; ``` ##### /app/routes/\*\*\\/\*.jsx ```ts 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 })); } ``` * #### ##### Description Trigger the registration after a merchant installs your app using the \`afterAuth\` hook. ##### Example ```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 }); ``` * #### ##### Description Import the \`@shopify/shopify-app-session-storage-prisma\` package to store sessions in your Prisma database. ##### /app/shopify.server.ts ```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 ``` * #### Using unauthenticated contexts ##### Description Create contexts for requests that don't come from Shopify. ##### /app/shopify.server.ts ```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; ``` ##### /app/routes/\*\*\\/\*.jsx ```ts 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 ```ts import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ##### /app/routes/auth/login.tsx ```ts 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/v1/authenticate) [Interact with the API on non-Shopify requests. - Unauthenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/v1/unauthenticated) ***