# 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. ```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; ``` ## shopifyApp Function to create a new Shopify API object. ### ShopifyAppGeneratedType Creates an object your app will use to interact with Shopify. #### Returns: ShopifyApp>`ShopifyApp` An object constructed using your appConfig. It has methods for interacting with Shopify. #### Params: - appConfig: Readonly export function shopifyApp< Config extends AppConfigArg, Resources extends ShopifyRestResources, Storage extends SessionStorage, Future extends FutureFlagOptions = Config['future'], >(appConfig: Readonly): ShopifyApp { const api = deriveApi(appConfig); const config = deriveConfig(appConfig, api.config); const logger = overrideLogger(api.logger); if (appConfig.webhooks) { api.webhooks.addHandlers(appConfig.webhooks); } const params: BasicParams = {api, config, logger}; const authStrategy = authStrategyFactory({ ...params, strategy: config.future.unstable_newEmbeddedAuthStrategy && config.isEmbeddedApp ? new TokenExchangeStrategy(params) : new AuthCodeFlowStrategy(params), }); const shopify: | AdminApp | AppStoreApp | SingleMerchantApp = { sessionStorage: config.sessionStorage, addDocumentResponseHeaders: addDocumentResponseHeadersFactory(params), registerWebhooks: registerWebhooksFactory(params), authenticate: { admin: authStrategy, flow: authenticateFlowFactory(params), public: authenticatePublicFactory(params), fulfillmentService: authenticateFulfillmentServiceFactory(params), webhook: authenticateWebhookFactory< Future, Resources, keyof Config['webhooks'] | MandatoryTopics >(params), }, unauthenticated: { admin: unauthenticatedAdminContextFactory(params), storefront: unauthenticatedStorefrontContextFactory(params), }, }; if ( isAppStoreApp(shopify, appConfig) || isSingleMerchantApp(shopify, appConfig) ) { shopify.login = loginFactory(params); } logDisabledFutureFlags(config, logger); return shopify as ShopifyApp; } ### AppDistribution ### AppStore value: `app_store` ### SingleMerchant value: `single_merchant` ### ShopifyAdmin value: `shopify_admin` ### AdminApp ### sessionStorage value: `SessionStorageType` - SessionStorageType: Config['sessionStorage'] extends SessionStorage ? Config['sessionStorage'] : SessionStorage - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } The `SessionStorage` instance you passed in as a config option. ### addDocumentResponseHeaders value: `AddDocumentResponseHeaders` - AddDocumentResponseHeaders: type AddDocumentResponseHeaders = (request: Request, headers: Headers) => void; - Headers: Record Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ### registerWebhooks value: `RegisterWebhooks` - RegisterWebhooks: type RegisterWebhooks = ( options: RegisterWebhooksOptions, ) => Promise; Register webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ### authenticate value: `Authenticate` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } Ways to authenticate requests from different surfaces across Shopify. ### unauthenticated value: `Unauthenticated>` - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources - Unauthenticated: 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {storefront} = await shopify.unauthenticated.storefront(shop); * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` */ storefront: GetUnauthenticatedStorefrontContext; } Ways to get Contexts from requests that do not originate from Shopify. ### AddDocumentResponseHeaders #### Returns: void #### Params: - request: Request - headers: Headers type AddDocumentResponseHeaders = (request: Request, headers: Headers) => void; ### RegisterWebhooks #### Returns: Promise #### Params: - options: RegisterWebhooksOptions type RegisterWebhooks = ( options: RegisterWebhooksOptions, ) => Promise; ### RegisterWebhooksOptions ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } The Shopify session used to register webhooks using the Admin API. ### Session Stores App information from logged in merchants so they can make authenticated requests to the Admin API. ### id value: `string` The unique identifier for the session. ### shop value: `string` The Shopify shop domain, such as `example.myshopify.com`. ### state value: `string` The state of the session. Used for the OAuth authentication code flow. ### isOnline value: `boolean` Whether the access token in the session is online or offline. ### scope value: `string` The desired scopes for the access token, at the time the session was created. ### expires value: `Date` The date the access token expires. ### accessToken value: `string` The access token for the session. ### onlineAccessInfo value: `OnlineAccessInfo` - OnlineAccessInfo: export interface OnlineAccessInfo { /** * How long the access token is valid for, in seconds. */ expires_in: number; /** * The effective set of scopes for the session. */ associated_user_scope: string; /** * The user associated with the access token. */ associated_user: OnlineAccessUser; } Information on the user for the session. Only present for online sessions. ### isActive value: `(scopes: string | string[] | AuthScopes) => boolean` - AuthScopes: class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray() { return [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. ### isScopeChanged value: `(scopes: string | string[] | AuthScopes) => boolean` - AuthScopes: class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray() { return [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } Whether the access token has the given scopes. ### isExpired value: `(withinMillisecondsOfExpiry?: number) => boolean` Whether the access token is expired. ### toObject value: `() => SessionParams` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } - SessionParams: export interface SessionParams { /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain. */ shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ state: string; /** * Whether the access token in the session is online or offline. */ isOnline: boolean; /** * The scopes for the access token. */ scope?: string; /** * The date the access token expires. */ expires?: Date; /** * The access token for the session. */ accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ onlineAccessInfo?: OnlineAccessInfo | StoredOnlineAccessInfo; /** * Additional properties of the session allowing for extension */ [key: string]: any; } Converts an object with data into a Session. ### equals value: `(other: Session) => boolean` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } Checks whether the given session is equal to this session. ### toPropertyArray value: `(returnUserData?: boolean) => [string, string | number | boolean][]` Converts the session into an array of key-value pairs. ### OnlineAccessInfo ### expires_in value: `number` How long the access token is valid for, in seconds. ### associated_user_scope value: `string` The effective set of scopes for the session. ### associated_user value: `OnlineAccessUser` - OnlineAccessUser: export interface OnlineAccessUser { /** * The user's ID. */ id: number; /** * The user's first name. */ first_name: string; /** * The user's last name. */ last_name: string; /** * The user's email address. */ email: string; /** * Whether the user has verified their email address. */ email_verified: boolean; /** * Whether the user is the account owner. */ account_owner: boolean; /** * The user's locale. */ locale: string; /** * Whether the user is a collaborator. */ collaborator: boolean; } The user associated with the access token. ### OnlineAccessUser ### id value: `number` The user's ID. ### first_name value: `string` The user's first name. ### last_name value: `string` The user's last name. ### email value: `string` The user's email address. ### email_verified value: `boolean` Whether the user has verified their email address. ### account_owner value: `boolean` Whether the user is the account owner. ### locale value: `string` The user's locale. ### collaborator value: `boolean` Whether the user is a collaborator. ### AuthScopes A class that represents a set of access token scopes. ### has value: `(scope: string | string[] | AuthScopes) => boolean` - AuthScopes: class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray() { return [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } Checks whether the current set of scopes includes the given one. ### equals value: `(otherScopes: string | string[] | AuthScopes) => boolean` - AuthScopes: class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray() { return [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } Checks whether the current set of scopes equals the given one. ### toString value: `() => string` Returns a comma-separated string with the current set of scopes. ### toArray value: `() => any[]` Returns an array with the current set of scopes. ### SessionParams ### [key: string] value: `any` ### id value: `string` The unique identifier for the session. ### shop value: `string` The Shopify shop domain. ### state value: `string` The state of the session. Used for the OAuth authentication code flow. ### isOnline value: `boolean` Whether the access token in the session is online or offline. ### scope value: `string` The scopes for the access token. ### expires value: `Date` The date the access token expires. ### accessToken value: `string` The access token for the session. ### onlineAccessInfo value: `OnlineAccessInfo | StoredOnlineAccessInfo` - OnlineAccessInfo: export interface OnlineAccessInfo { /** * How long the access token is valid for, in seconds. */ expires_in: number; /** * The effective set of scopes for the session. */ associated_user_scope: string; /** * The user associated with the access token. */ associated_user: OnlineAccessUser; } - StoredOnlineAccessInfo: Omit & { associated_user: Partial; } Information on the user for the session. Only present for online sessions. ### Authenticate ### admin value: `AuthenticateAdmin>` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - AuthenticateAdmin: export type AuthenticateAdmin< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources 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. ### flow value: `AuthenticateFlow>` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources - AuthenticateFlow: export type AuthenticateFlow< Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access the API, and the payload of the request. If there is no session for the Request, this will return an HTTP 400 error. Note that this will always be a POST request. ### fulfillmentService value: `AuthenticateFulfillmentService>` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources - AuthenticateFulfillmentService: export type AuthenticateFulfillmentService< Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; Authenticate a request from a fulfillment service and get back an authenticated context. ### public value: `AuthenticatePublic` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - AuthenticatePublic: FeatureEnabled extends true ? AuthenticatePublicObject : AuthenticatePublicLegacy Authenticate a public request and get back a session token. ### webhook value: `AuthenticateWebhook< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources - AuthenticateWebhook: export type AuthenticateWebhook< Future extends FutureFlagOptions, Resources extends ShopifyRestResources, Topics = string | number | symbol, > = (request: Request) => Promise>; - MandatoryTopics: 'CUSTOMERS_DATA_REQUEST' | 'CUSTOMERS_REDACT' | 'SHOP_REDACT' Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request ### AuthenticateAdmin #### Returns: Promise> #### Params: - request: Request export type AuthenticateAdmin< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; ### NonEmbeddedAdminContext ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } 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. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request. ### billing value: `BillingContext` - BillingContext: export interface BillingContext { /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Requesting billing right away. * Call `billing.request` in the `onFailure` callback to immediately redirect to the Shopify page to request payment. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * isTest: true, * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * 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 * Redirect to a plan selection page. * When the app has multiple plans, create a page in your App that allows the merchant to select a plan. If a merchant does not have the required plan you can redirect them to page in your app to select one. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, redirect } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN, ANNUAL_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN, ANNUAL_PLAN], * isTest: true, * onFailure: () => redirect('/select-plan'), * }); * * const subscription = billingCheck.appSubscriptions[0]; * console.log(`Shop is on ${subscription.name} (id ${subscription.id})`); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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 * Requesting billing with line items * Call `billing.request` with the `v3_lineItemBilling` future flag enabled * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * isTest: true, * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * { * amount: 1, * currencyCode: 'USD', * interval: BillingInterval.Usage. * terms: '1 dollar per 1000 emails', * }, * ], * }, * } * future: {v3_lineItemBilling: true} * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ require: ( options: RequireBillingOptions, ) => Promise; /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Check what billing plans a merchant is subscribed to. * Use billing.check if you want to determine which plans are in use. Unlike `require`, `check` does not * throw an error if no active billing plans are present. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const { hasActivePayment, appSubscriptions } = await billing.check({ * plans: [MONTHLY_PLAN], * isTest: false, * }); * console.log(hasActivePayment) * console.log(appSubscriptions) * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * */ check: ( options: CheckBillingOptions, ) => Promise; /** * Requests payment for the plan. * * @returns Redirects to the confirmation URL for the payment. * * @example * Using a custom return URL. * Change where the merchant is returned to after approving the purchase using the `returnUrl` option. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ * plan: MONTHLY_PLAN, * isTest: true, * returnUrl: 'https://admin.shopify.com/store/my-store/apps/my-app/billing-page', * }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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 { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * const subscription = billingCheck.appSubscriptions[0]; * const cancelledSubscription = await billing.cancel({ * subscriptionId: subscription.id, * isTest: true, * prorate: true, * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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; } Billing methods for this store, based on the plans defined in the `billing` config option. ### cors value: `EnsureCORSFunction` - EnsureCORSFunction: export interface EnsureCORSFunction { (response: Response): Response; } A function that ensures the CORS headers are set correctly for the response. ### AdminApiContext ### rest value: `RestClientWithResources` - RestClientWithResources: RemixRestClient & {resources: Resources} - RestClient: export class RestClient { public static config: ConfigInterface; public static formatPaths: boolean; static LINK_HEADER_REGEXP = /<([^<]+)>; rel="([^"]+)"/; static DEFAULT_LIMIT = '50'; static RETRY_WAIT_TIME = 1000; static readonly DEPRECATION_ALERT_DELAY = 300000; loggedDeprecations: Record = {}; readonly client: AdminRestApiClient; readonly session: Session; readonly apiVersion: ApiVersion; public constructor({session, apiVersion}: RestClientParams) { const config = this.restClass().config; if (!config.isCustomStoreApp && !session.accessToken) { throw new ShopifyErrors.MissingRequiredArgument( 'Missing access token when creating REST client', ); } if (apiVersion) { const message = apiVersion === config.apiVersion ? `REST client has a redundant API version override to the default ${apiVersion}` : `REST client overriding default API version ${config.apiVersion} with ${apiVersion}`; logger(config).debug(message); } const customStoreAppAccessToken = config.adminApiAccessToken ?? config.apiSecretKey; this.session = session; this.apiVersion = apiVersion ?? config.apiVersion; this.client = createAdminRestApiClient({ scheme: config.hostScheme, storeDomain: session.shop, apiVersion: apiVersion ?? config.apiVersion, accessToken: config.isCustomStoreApp ? customStoreAppAccessToken : session.accessToken!, customFetchApi: abstractFetch, logger: clientLoggerFactory(config), userAgentPrefix: getUserAgent(config), defaultRetryTime: this.restClass().RETRY_WAIT_TIME, formatPaths: this.restClass().formatPaths, }); } /** * Performs a GET request on the given path. */ public async get(params: GetRequestParams) { return this.request({method: Method.Get, ...params}); } /** * Performs a POST request on the given path. */ public async post(params: PostRequestParams) { return this.request({method: Method.Post, ...params}); } /** * Performs a PUT request on the given path. */ public async put(params: PutRequestParams) { return this.request({method: Method.Put, ...params}); } /** * Performs a DELETE request on the given path. */ public async delete(params: DeleteRequestParams) { return this.request({method: Method.Delete, ...params}); } protected async request( params: RequestParams, ): Promise> { const requestParams = { headers: { ...params.extraHeaders, ...(params.type ? {'Content-Type': params.type.toString()} : {}), }, retries: params.tries ? params.tries - 1 : undefined, searchParams: params.query, }; let response: Response; switch (params.method) { case Method.Get: response = await this.client.get(params.path, requestParams); break; case Method.Put: response = await this.client.put(params.path, { ...requestParams, data: params.data!, }); break; case Method.Post: response = await this.client.post(params.path, { ...requestParams, data: params.data!, }); break; case Method.Delete: response = await this.client.delete(params.path, requestParams); break; default: throw new ShopifyErrors.InvalidRequestError( `Unsupported request method '${params.method}'`, ); } const body: any = await response.json(); const responseHeaders = canonicalizeHeaders( Object.fromEntries(response.headers.entries()), ); if (!response.ok) { throwFailedRequest(body, (params.tries ?? 1) > 1, response); } const requestReturn: RestRequestReturn = { body, headers: responseHeaders, }; await this.logDeprecations( { method: params.method, url: params.path, headers: requestParams.headers, body: params.data ? JSON.stringify(params.data) : undefined, }, requestReturn, ); const link = response.headers.get('Link'); if (link !== undefined) { const pageInfo: PageInfo = { limit: params.query?.limit ? params.query?.limit.toString() : RestClient.DEFAULT_LIMIT, }; if (link) { const links = link.split(', '); for (const link of links) { const parsedLink = link.match(RestClient.LINK_HEADER_REGEXP); if (!parsedLink) { continue; } const linkRel = parsedLink[2]; const linkUrl = new URL(parsedLink[1]); const linkFields = linkUrl.searchParams.get('fields'); const linkPageToken = linkUrl.searchParams.get('page_info'); if (!pageInfo.fields && linkFields) { pageInfo.fields = linkFields.split(','); } if (linkPageToken) { switch (linkRel) { case 'previous': pageInfo.previousPageUrl = parsedLink[1]; pageInfo.prevPage = this.buildRequestParams(parsedLink[1]); break; case 'next': pageInfo.nextPageUrl = parsedLink[1]; pageInfo.nextPage = this.buildRequestParams(parsedLink[1]); break; } } } } requestReturn.pageInfo = pageInfo; } return requestReturn; } private restClass() { return this.constructor as typeof RestClient; } private buildRequestParams(newPageUrl: string): PageInfoParams { const pattern = `^/admin/api/[^/]+/(.*).json$`; const url = new URL(newPageUrl); const path = url.pathname.replace(new RegExp(pattern), '$1'); return { path, query: Object.fromEntries(url.searchParams.entries()), }; } private async logDeprecations( request: NormalizedRequest, response: RestRequestReturn, ) { const config = this.restClass().config; const deprecationReason = getHeader( response.headers, 'X-Shopify-API-Deprecated-Reason', ); if (deprecationReason) { const deprecation: DeprecationInterface = { message: deprecationReason, path: request.url, }; if (request.body) { // This can only be a string, since we're always converting the body before calling this method deprecation.body = `${(request.body as string).substring(0, 100)}...`; } const depHash = await createSHA256HMAC( config.apiSecretKey, JSON.stringify(deprecation), HashFormat.Hex, ); if ( !Object.keys(this.loggedDeprecations).includes(depHash) || Date.now() - this.loggedDeprecations[depHash] >= RestClient.DEPRECATION_ALERT_DELAY ) { this.loggedDeprecations[depHash] = Date.now(); const stack = new Error().stack; const message = `API Deprecation Notice ${new Date().toLocaleString()} : ${JSON.stringify( deprecation, )} - Stack Trace: ${stack}`; await logger(config).warning(message); } } } } 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. ### graphql value: `GraphQLClient` - GraphQLClient: export type GraphQLClient = < Operation extends keyof Operations, >( query: Operation, options?: GraphQLQueryOptions, ) => Promise>; Methods for interacting with the Shopify Admin GraphQL API ### RemixRestClient ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } ### get value: `(params: GetRequestParams) => Promise` - GetRequestParams: export interface GetRequestParams { /** * The path to the resource, relative to the API version root. */ path: string; /** * The type of data expected in the response. */ type?: DataType; /** * The request body. */ data?: Record | string; /** * Query parameters to be sent with the request. */ query?: SearchParams; /** * Additional headers to be sent with the request. */ extraHeaders?: HeaderParams; /** * The maximum number of times the request can be made if it fails with a throttling or server error. */ tries?: number; } Performs a GET request on the given path. ### post value: `(params: PostRequestParams) => Promise` - PostRequestParams: GetRequestParams & { data: Record | string; } Performs a POST request on the given path. ### put value: `(params: PostRequestParams) => Promise` - PostRequestParams: GetRequestParams & { data: Record | string; } Performs a PUT request on the given path. ### delete value: `(params: GetRequestParams) => Promise` - GetRequestParams: export interface GetRequestParams { /** * The path to the resource, relative to the API version root. */ path: string; /** * The type of data expected in the response. */ type?: DataType; /** * The request body. */ data?: Record | string; /** * Query parameters to be sent with the request. */ query?: SearchParams; /** * Additional headers to be sent with the request. */ extraHeaders?: HeaderParams; /** * The maximum number of times the request can be made if it fails with a throttling or server error. */ tries?: number; } Performs a DELETE request on the given path. ### GetRequestParams ### path value: `string` The path to the resource, relative to the API version root. ### type value: `DataType` - DataType: export enum DataType { JSON = 'application/json', GraphQL = 'application/graphql', URLEncoded = 'application/x-www-form-urlencoded', } The type of data expected in the response. ### data value: `string | Record` The request body. ### query value: `SearchParams` Query parameters to be sent with the request. ### extraHeaders value: `HeaderParams` - HeaderParams: Record Additional headers to be sent with the request. ### tries value: `number` The maximum number of times the request can be made if it fails with a throttling or server error. ### DataType ### JSON value: `application/json` ### GraphQL value: `application/graphql` ### URLEncoded value: `application/x-www-form-urlencoded` ### GraphQLClient #### Returns: interface Promise { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; }, interface Promise {}, Promise: PromiseConstructor, interface Promise { readonly [Symbol.toStringTag]: string; }, interface Promise { /** * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The * resolved value cannot be modified from the callback. * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). * @returns A Promise for the completion of the callback. */ finally(onfinally?: (() => void) | undefined | null): Promise; } #### Params: - query: Operation extends keyof Operations - options: GraphQLQueryOptions export type GraphQLClient = < Operation extends keyof Operations, >( query: Operation, options?: GraphQLQueryOptions, ) => Promise>; ### GraphQLQueryOptions ### variables value: `ApiClientRequestOptions["variables"]` - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } The variables to pass to the operation. ### apiVersion value: `ApiVersion` - ApiVersion: export enum ApiVersion { October22 = '2022-10', January23 = '2023-01', April23 = '2023-04', July23 = '2023-07', October23 = '2023-10', January24 = '2024-01', April24 = '2024-04', Unstable = 'unstable', } The version of the API to use for the request. ### headers value: `Record` Additional headers to include in the request. ### tries value: `number` The total number of times to try the request if it fails. ### ApiVersion ### October22 value: `2022-10` ### January23 value: `2023-01` ### April23 value: `2023-04` ### July23 value: `2023-07` ### October23 value: `2023-10` ### January24 value: `2024-01` ### April24 value: `2024-04` ### Unstable value: `unstable` ### BillingContext ### require value: `(options: RequireBillingOptions) => Promise` - RequireBillingOptions: 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; } - BillingCheckResponseObject: export interface BillingCheckResponseObject { /** * Whether the user has an active payment method. */ hasActivePayment: boolean; /** * The one-time purchases the shop has. */ oneTimePurchases: OneTimePurchase[]; /** * The active subscriptions the shop has. */ appSubscriptions: AppSubscription[]; } - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } Checks if the shop has an active payment for any plan defined in the `billing` config option. ### check value: `(options: CheckBillingOptions) => Promise` - BillingCheckResponseObject: export interface BillingCheckResponseObject { /** * Whether the user has an active payment method. */ hasActivePayment: boolean; /** * The one-time purchases the shop has. */ oneTimePurchases: OneTimePurchase[]; /** * The active subscriptions the shop has. */ appSubscriptions: AppSubscription[]; } - CheckBillingOptions: export interface CheckBillingOptions extends Omit { /** * The plans to check for. Must be one of the values defined in the `billing` config option. */ plans: (keyof Config['billing'])[]; } - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } Checks if the shop has an active payment for any plan defined in the `billing` config option. ### request value: `(options: RequestBillingOptions) => Promise` - RequestBillingOptions: export interface RequestBillingOptions extends Omit { /** * The plan to request. Must be one of the values defined in the `billing` config option. */ plan: keyof Config['billing']; /** * Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged. */ isTest?: boolean; /** * The URL to return to after the merchant approves the payment. */ returnUrl?: string; } - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } Requests payment for the plan. ### cancel value: `(options: CancelBillingOptions) => Promise` - AppSubscription: export interface AppSubscription { /** * The ID of the app subscription. */ id: string; /** * The name of the purchased plan. */ name: string; /** * Whether this is a test subscription. */ test: boolean; /* * The line items for this plan. This will become mandatory in v10. */ lineItems?: ActiveSubscriptionLineItem[]; } - CancelBillingOptions: 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; /* * Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged. */ isTest?: boolean; } - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } Cancels an ongoing subscription, given its ID. ### RequireBillingOptions ### plans value: `(keyof Config["billing"])[]` The plans to check for. Must be one of the values defined in the `billing` config option. ### onFailure value: `(error: any) => Promise` How to handle the request if the shop doesn't have an active payment for any plan. ### isTest value: `boolean` Whether to consider test purchases. ### BillingCheckResponseObject ### hasActivePayment value: `boolean` Whether the user has an active payment method. ### oneTimePurchases value: `OneTimePurchase[]` - OneTimePurchase: export interface OneTimePurchase { /** * The ID of the one-time purchase. */ id: string; /** * The name of the purchased plan. */ name: string; /** * Whether this is a test purchase. */ test: boolean; /** * The status of the one-time purchase. */ status: string; } The one-time purchases the shop has. ### appSubscriptions value: `AppSubscription[]` - AppSubscription: export interface AppSubscription { /** * The ID of the app subscription. */ id: string; /** * The name of the purchased plan. */ name: string; /** * Whether this is a test subscription. */ test: boolean; /* * The line items for this plan. This will become mandatory in v10. */ lineItems?: ActiveSubscriptionLineItem[]; } The active subscriptions the shop has. ### OneTimePurchase ### id value: `string` The ID of the one-time purchase. ### name value: `string` The name of the purchased plan. ### test value: `boolean` Whether this is a test purchase. ### status value: `string` The status of the one-time purchase. ### AppSubscription ### id value: `string` The ID of the app subscription. ### name value: `string` The name of the purchased plan. ### test value: `boolean` Whether this is a test subscription. ### lineItems value: `ActiveSubscriptionLineItem[]` - ActiveSubscriptionLineItem: export interface ActiveSubscriptionLineItem { /* * The ID of the line item. */ id: string; /* * The details of the plan. */ plan: AppPlan; } ### ActiveSubscriptionLineItem ### id value: `string` ### plan value: `AppPlan` - AppPlan: export interface AppPlan { /* * The pricing details of the plan. */ pricingDetails: RecurringAppPlan | UsageAppPlan; } ### AppPlan ### pricingDetails value: `RecurringAppPlan | UsageAppPlan` - AppPlan: export interface AppPlan { /* * The pricing details of the plan. */ pricingDetails: RecurringAppPlan | UsageAppPlan; } - RecurringAppPlan: export interface RecurringAppPlan { /* * The interval for this plan is charged on. */ interval: BillingInterval.Every30Days | BillingInterval.Annual; /* * The price of the plan. */ price: Money; /* * The discount applied to the plan. */ discount: AppPlanDiscount; } - UsageAppPlan: export interface UsageAppPlan { /* * The total usage records for interval. */ balanceUsed: Money; /* * The capped amount prevents the merchant from being charged for any usage over that amount during a billing period. */ cappedAmount: Money; /* * The terms and conditions for app usage pricing. */ terms: string; } ### RecurringAppPlan ### interval value: `BillingInterval.Every30Days | BillingInterval.Annual` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } ### price value: `Money` - Money: interface Money { amount: number; currencyCode: string; } ### discount value: `AppPlanDiscount` - AppPlan: export interface AppPlan { /* * The pricing details of the plan. */ pricingDetails: RecurringAppPlan | UsageAppPlan; } - AppPlanDiscount: export interface AppPlanDiscount { /* * The total number of intervals the discount applies to. */ durationLimitInIntervals: number; /* * The remaining number of intervals the discount applies to. */ remainingDurationInIntervals: number; /* * The price after the discount is applied. */ priceAfterDiscount: Money; /* * The value of the discount applied every billing interval. */ value: AppPlanDiscountAmount; } ### BillingInterval ### OneTime value: `ONE_TIME` ### Every30Days value: `EVERY_30_DAYS` ### Annual value: `ANNUAL` ### Usage value: `USAGE` ### Money ### amount value: `number` ### currencyCode value: `string` ### AppPlanDiscount ### durationLimitInIntervals value: `number` ### remainingDurationInIntervals value: `number` ### priceAfterDiscount value: `Money` - Money: interface Money { amount: number; currencyCode: string; } ### value value: `AppPlanDiscountAmount` - AppPlan: export interface AppPlan { /* * The pricing details of the plan. */ pricingDetails: RecurringAppPlan | UsageAppPlan; } - AppPlanDiscount: export interface AppPlanDiscount { /* * The total number of intervals the discount applies to. */ durationLimitInIntervals: number; /* * The remaining number of intervals the discount applies to. */ remainingDurationInIntervals: number; /* * The price after the discount is applied. */ priceAfterDiscount: Money; /* * The value of the discount applied every billing interval. */ value: AppPlanDiscountAmount; } - AppPlanDiscountAmount: BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage ### BillingConfigSubscriptionPlanDiscountAmount ### amount value: `number` The amount to discount. Cannot be set if `percentage` is set. ### percentage value: `never` The percentage to discount. Cannot be set if `amount` is set. ### BillingConfigSubscriptionPlanDiscountPercentage ### amount value: `never` The amount to discount. Cannot be set if `percentage` is set. ### percentage value: `number` The percentage to discount. Cannot be set if `amount` is set. ### UsageAppPlan ### balanceUsed value: `Money` - Money: interface Money { amount: number; currencyCode: string; } ### cappedAmount value: `Money` - Money: interface Money { amount: number; currencyCode: string; } ### terms value: `string` ### CheckBillingOptions ### plans value: `(keyof Config["billing"])[]` The plans to check for. Must be one of the values defined in the `billing` config option. ### isTest value: `boolean` Whether to consider test purchases. ### RequestBillingOptions ### plan value: `keyof Config["billing"]` The plan to request. Must be one of the values defined in the `billing` config option. ### isTest value: `boolean` Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged. ### returnUrl value: `string` The URL to return to after the merchant approves the payment. ### CancelBillingOptions ### subscriptionId value: `string` The ID of the subscription to cancel. ### prorate value: `boolean` Whether to prorate the cancellation. ### isTest value: `boolean` ### EmbeddedAdminContext ### sessionToken value: `JwtPayload` - JwtPayload: export interface JwtPayload { /** * The shop's admin domain. */ iss: string; /** * The shop's domain. */ dest: string; /** * The client ID of the receiving app. */ aud: string; /** * The User that the session token is intended for. */ sub: string; /** * When the session token expires. */ exp: number; /** * When the session token activates. */ nbf: number; /** * When the session token was issued. */ iat: number; /** * A secure random UUID. */ jti: string; /** * A unique session ID per user and app. */ sid: string; } The decoded and validated session token for the request. Returned only if `isEmbeddedApp` is `true`. ### redirect value: `RedirectFunction` - RedirectFunction: export type RedirectFunction = ( url: string, init?: RedirectInit, ) => TypedResponse; 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`. ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } 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. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request. ### billing value: `BillingContext` - BillingContext: export interface BillingContext { /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Requesting billing right away. * Call `billing.request` in the `onFailure` callback to immediately redirect to the Shopify page to request payment. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * isTest: true, * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * 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 * Redirect to a plan selection page. * When the app has multiple plans, create a page in your App that allows the merchant to select a plan. If a merchant does not have the required plan you can redirect them to page in your app to select one. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, redirect } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN, ANNUAL_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN, ANNUAL_PLAN], * isTest: true, * onFailure: () => redirect('/select-plan'), * }); * * const subscription = billingCheck.appSubscriptions[0]; * console.log(`Shop is on ${subscription.name} (id ${subscription.id})`); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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 * Requesting billing with line items * Call `billing.request` with the `v3_lineItemBilling` future flag enabled * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * isTest: true, * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * lineItems: [ * { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * { * amount: 1, * currencyCode: 'USD', * interval: BillingInterval.Usage. * terms: '1 dollar per 1000 emails', * }, * ], * }, * } * future: {v3_lineItemBilling: true} * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ require: ( options: RequireBillingOptions, ) => Promise; /** * Checks if the shop has an active payment for any plan defined in the `billing` config option. * * @returns A promise that resolves to an object containing the active purchases for the shop. * * @example * Check what billing plans a merchant is subscribed to. * Use billing.check if you want to determine which plans are in use. Unlike `require`, `check` does not * throw an error if no active billing plans are present. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const { hasActivePayment, appSubscriptions } = await billing.check({ * plans: [MONTHLY_PLAN], * isTest: false, * }); * console.log(hasActivePayment) * console.log(appSubscriptions) * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * amount: 5, * currencyCode: 'USD', * interval: BillingInterval.Every30Days, * }, * [ANNUAL_PLAN]: { * amount: 50, * currencyCode: 'USD', * interval: BillingInterval.Annual, * }, * } * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * */ check: ( options: CheckBillingOptions, ) => Promise; /** * Requests payment for the plan. * * @returns Redirects to the confirmation URL for the payment. * * @example * Using a custom return URL. * Change where the merchant is returned to after approving the purchase using the `returnUrl` option. * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ * plan: MONTHLY_PLAN, * isTest: true, * returnUrl: 'https://admin.shopify.com/store/my-store/apps/my-app/billing-page', * }), * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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 { LoaderFunctionArgs } from "@remix-run/node"; * import { authenticate, MONTHLY_PLAN } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { billing } = await authenticate.admin(request); * const billingCheck = await billing.require({ * plans: [MONTHLY_PLAN], * onFailure: async () => billing.request({ plan: MONTHLY_PLAN }), * }); * * const subscription = billingCheck.appSubscriptions[0]; * const cancelledSubscription = await billing.cancel({ * subscriptionId: subscription.id, * isTest: true, * prorate: true, * }); * * // App logic * }; * ``` * ```ts * // shopify.server.ts * import { shopifyApp, BillingInterval } from "@shopify/shopify-app-remix/server"; * * export const MONTHLY_PLAN = 'Monthly subscription'; * export const ANNUAL_PLAN = 'Annual subscription'; * * const shopify = shopifyApp({ * // ...etc * billing: { * [MONTHLY_PLAN]: { * 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; } Billing methods for this store, based on the plans defined in the `billing` config option. ### cors value: `EnsureCORSFunction` - EnsureCORSFunction: export interface EnsureCORSFunction { (response: Response): Response; } A function that ensures the CORS headers are set correctly for the response. ### JwtPayload ### iss value: `string` The shop's admin domain. ### dest value: `string` The shop's domain. ### aud value: `string` The client ID of the receiving app. ### sub value: `string` The User that the session token is intended for. ### exp value: `number` When the session token expires. ### nbf value: `number` When the session token activates. ### iat value: `number` When the session token was issued. ### jti value: `string` A secure random UUID. ### sid value: `string` A unique session ID per user and app. ### RedirectFunction #### Returns: TypedResponse #### Params: - url: string - init: RedirectInit export type RedirectFunction = ( url: string, init?: RedirectInit, ) => TypedResponse; ### AuthenticateFlow #### Returns: Promise> #### Params: - request: Request export type AuthenticateFlow< Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; ### FlowContext ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } A session with an offline token for the shop. Returned only if there is a session for the shop. ### payload value: `any` The payload from the Flow request. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } An admin context for the Flow request. Returned only if there is a session for the shop. ### AuthenticateFulfillmentService #### Returns: Promise> #### Params: - request: Request export type AuthenticateFulfillmentService< Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise>; ### FulfillmentServiceContext ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } A session with an offline token for the shop. Returned only if there is a session for the shop. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } An admin context for the fulfillment service request. Returned only if there is a session for the shop. ### payload value: `Record & { kind: string; }` The payload from the fulfillment service request. ### AuthenticatePublicObject ### checkout value: `AuthenticateCheckout` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - AuthenticateCheckout: export type AuthenticateCheckout = ( request: Request, options?: AuthenticateCheckoutOptions, ) => Promise; Authenticate a request from a checkout extension ### appProxy value: `AuthenticateAppProxy` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } - AuthenticateAppProxy: export type AuthenticateAppProxy = ( request: Request, ) => Promise; Authenticate a request from an app proxy ### AuthenticateCheckout #### Returns: Promise #### Params: - request: Request - options: AuthenticateCheckoutOptions export type AuthenticateCheckout = ( request: Request, options?: AuthenticateCheckoutOptions, ) => Promise; ### AuthenticateCheckoutOptions ### corsHeaders value: `string[]` ### CheckoutContext Authenticated Context for a checkout request ### sessionToken value: `JwtPayload` - JwtPayload: export interface JwtPayload { /** * The shop's admin domain. */ iss: string; /** * The shop's domain. */ dest: string; /** * The client ID of the receiving app. */ aud: string; /** * The User that the session token is intended for. */ sub: string; /** * When the session token expires. */ exp: number; /** * When the session token activates. */ nbf: number; /** * When the session token was issued. */ iat: number; /** * A secure random UUID. */ jti: string; /** * A unique session ID per user and app. */ sid: string; } 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). ### cors value: `EnsureCORSFunction` - EnsureCORSFunction: export interface EnsureCORSFunction { (response: Response): Response; } A function that ensures the CORS headers are set correctly for the response. ### AuthenticateAppProxy #### Returns: Promise #### Params: - request: Request export type AuthenticateAppProxy = ( request: Request, ) => Promise; ### AppProxyContext ### session value: `undefined` 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. ### admin value: `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. ### storefront value: `undefined` No session is available for the shop that made this request. Therefore no method for interacting with the Storefront API is available. ### liquid value: `LiquidResponseFunction` - LiquidResponseFunction: export type LiquidResponseFunction = ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response; A utility for creating a Liquid Response. ### LiquidResponseFunction #### Returns: Response #### Params: - body: string - initAndOptions: number | (ResponseInit & Options) export type LiquidResponseFunction = ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response; ### Options ### layout value: `boolean` Whether to use the shop's theme layout around the Liquid content. ### AppProxyContextWithSession ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } 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. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request. ### storefront value: `StorefrontContext` - StorefrontContext: export interface StorefrontContext { /** * Method for interacting with the Shopify Storefront GraphQL API * * If you're getting incorrect type hints in the Shopify template, follow [these instructions](https://github.com/Shopify/shopify-app-template-remix/tree/main#incorrect-graphql-hints). * * {@link https://shopify.dev/docs/api/storefront} * * @example * Querying the GraphQL API. * Use `storefront.graphql` to make query / mutation requests. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { storefront } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { storefront } = await authenticate.public.appProxy(request); * * try { * const response = await storefront.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // { errors: { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Method for interacting with the Shopify Storefront Graphql API for the store that made the request. ### liquid value: `LiquidResponseFunction` - LiquidResponseFunction: export type LiquidResponseFunction = ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response; A utility for creating a Liquid Response. ### StorefrontContext ### graphql value: `GraphQLClient` - GraphQLClient: export type GraphQLClient = < Operation extends keyof Operations, >( query: Operation, options?: GraphQLQueryOptions, ) => Promise>; 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). ### AuthenticateWebhook #### Returns: Promise> #### Params: - request: Request export type AuthenticateWebhook< Future extends FutureFlagOptions, Resources extends ShopifyRestResources, Topics = string | number | symbol, > = (request: Request) => Promise>; ### WebhookContextWithoutSession ### session value: `undefined` ### admin value: `undefined` ### apiVersion value: `string` The API version used for the webhook. ### shop value: `string` The shop where the webhook was triggered. ### topic value: `Topics` The topic of the webhook. ### webhookId value: `string` A unique ID for the webhook. Useful to keep track of which events your app has already processed. ### payload value: `Record` The payload from the webhook request. ### subTopic value: `string` The sub-topic of the webhook. This is only available for certain webhooks. ### WebhookContextWithSession ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } A session with an offline token for the shop. Returned only if there is a session for the shop. ### admin value: `WebhookAdminContext` - AdminContext: Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext : EmbeddedAdminContext - WebhookAdminContext: FeatureEnabled extends true ? AdminApiContext : LegacyWebhookAdminApiContext An admin context for the webhook. Returned only if there is a session for the shop. ### apiVersion value: `string` The API version used for the webhook. ### shop value: `string` The shop where the webhook was triggered. ### topic value: `Topics` The topic of the webhook. ### webhookId value: `string` A unique ID for the webhook. Useful to keep track of which events your app has already processed. ### payload value: `Record` The payload from the webhook request. ### subTopic value: `string` The sub-topic of the webhook. This is only available for certain webhooks. ### LegacyWebhookAdminApiContext ### rest value: `RestClient & Resources` - RestClient: export class RestClient { public static config: ConfigInterface; public static formatPaths: boolean; static LINK_HEADER_REGEXP = /<([^<]+)>; rel="([^"]+)"/; static DEFAULT_LIMIT = '50'; static RETRY_WAIT_TIME = 1000; static readonly DEPRECATION_ALERT_DELAY = 300000; loggedDeprecations: Record = {}; readonly client: AdminRestApiClient; readonly session: Session; readonly apiVersion: ApiVersion; public constructor({session, apiVersion}: RestClientParams) { const config = this.restClass().config; if (!config.isCustomStoreApp && !session.accessToken) { throw new ShopifyErrors.MissingRequiredArgument( 'Missing access token when creating REST client', ); } if (apiVersion) { const message = apiVersion === config.apiVersion ? `REST client has a redundant API version override to the default ${apiVersion}` : `REST client overriding default API version ${config.apiVersion} with ${apiVersion}`; logger(config).debug(message); } const customStoreAppAccessToken = config.adminApiAccessToken ?? config.apiSecretKey; this.session = session; this.apiVersion = apiVersion ?? config.apiVersion; this.client = createAdminRestApiClient({ scheme: config.hostScheme, storeDomain: session.shop, apiVersion: apiVersion ?? config.apiVersion, accessToken: config.isCustomStoreApp ? customStoreAppAccessToken : session.accessToken!, customFetchApi: abstractFetch, logger: clientLoggerFactory(config), userAgentPrefix: getUserAgent(config), defaultRetryTime: this.restClass().RETRY_WAIT_TIME, formatPaths: this.restClass().formatPaths, }); } /** * Performs a GET request on the given path. */ public async get(params: GetRequestParams) { return this.request({method: Method.Get, ...params}); } /** * Performs a POST request on the given path. */ public async post(params: PostRequestParams) { return this.request({method: Method.Post, ...params}); } /** * Performs a PUT request on the given path. */ public async put(params: PutRequestParams) { return this.request({method: Method.Put, ...params}); } /** * Performs a DELETE request on the given path. */ public async delete(params: DeleteRequestParams) { return this.request({method: Method.Delete, ...params}); } protected async request( params: RequestParams, ): Promise> { const requestParams = { headers: { ...params.extraHeaders, ...(params.type ? {'Content-Type': params.type.toString()} : {}), }, retries: params.tries ? params.tries - 1 : undefined, searchParams: params.query, }; let response: Response; switch (params.method) { case Method.Get: response = await this.client.get(params.path, requestParams); break; case Method.Put: response = await this.client.put(params.path, { ...requestParams, data: params.data!, }); break; case Method.Post: response = await this.client.post(params.path, { ...requestParams, data: params.data!, }); break; case Method.Delete: response = await this.client.delete(params.path, requestParams); break; default: throw new ShopifyErrors.InvalidRequestError( `Unsupported request method '${params.method}'`, ); } const body: any = await response.json(); const responseHeaders = canonicalizeHeaders( Object.fromEntries(response.headers.entries()), ); if (!response.ok) { throwFailedRequest(body, (params.tries ?? 1) > 1, response); } const requestReturn: RestRequestReturn = { body, headers: responseHeaders, }; await this.logDeprecations( { method: params.method, url: params.path, headers: requestParams.headers, body: params.data ? JSON.stringify(params.data) : undefined, }, requestReturn, ); const link = response.headers.get('Link'); if (link !== undefined) { const pageInfo: PageInfo = { limit: params.query?.limit ? params.query?.limit.toString() : RestClient.DEFAULT_LIMIT, }; if (link) { const links = link.split(', '); for (const link of links) { const parsedLink = link.match(RestClient.LINK_HEADER_REGEXP); if (!parsedLink) { continue; } const linkRel = parsedLink[2]; const linkUrl = new URL(parsedLink[1]); const linkFields = linkUrl.searchParams.get('fields'); const linkPageToken = linkUrl.searchParams.get('page_info'); if (!pageInfo.fields && linkFields) { pageInfo.fields = linkFields.split(','); } if (linkPageToken) { switch (linkRel) { case 'previous': pageInfo.previousPageUrl = parsedLink[1]; pageInfo.prevPage = this.buildRequestParams(parsedLink[1]); break; case 'next': pageInfo.nextPageUrl = parsedLink[1]; pageInfo.nextPage = this.buildRequestParams(parsedLink[1]); break; } } } } requestReturn.pageInfo = pageInfo; } return requestReturn; } private restClass() { return this.constructor as typeof RestClient; } private buildRequestParams(newPageUrl: string): PageInfoParams { const pattern = `^/admin/api/[^/]+/(.*).json$`; const url = new URL(newPageUrl); const path = url.pathname.replace(new RegExp(pattern), '$1'); return { path, query: Object.fromEntries(url.searchParams.entries()), }; } private async logDeprecations( request: NormalizedRequest, response: RestRequestReturn, ) { const config = this.restClass().config; const deprecationReason = getHeader( response.headers, 'X-Shopify-API-Deprecated-Reason', ); if (deprecationReason) { const deprecation: DeprecationInterface = { message: deprecationReason, path: request.url, }; if (request.body) { // This can only be a string, since we're always converting the body before calling this method deprecation.body = `${(request.body as string).substring(0, 100)}...`; } const depHash = await createSHA256HMAC( config.apiSecretKey, JSON.stringify(deprecation), HashFormat.Hex, ); if ( !Object.keys(this.loggedDeprecations).includes(depHash) || Date.now() - this.loggedDeprecations[depHash] >= RestClient.DEPRECATION_ALERT_DELAY ) { this.loggedDeprecations[depHash] = Date.now(); const stack = new Error().stack; const message = `API Deprecation Notice ${new Date().toLocaleString()} : ${JSON.stringify( deprecation, )} - Stack Trace: ${stack}`; await logger(config).warning(message); } } } } A REST client. ### graphql value: `InstanceType` A GraphQL client. ### RestClient ### loggedDeprecations value: `Record` ### client value: `AdminRestApiClient` ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } ### apiVersion value: `ApiVersion` - ApiVersion: export enum ApiVersion { October22 = '2022-10', January23 = '2023-01', April23 = '2023-04', July23 = '2023-07', October23 = '2023-10', January24 = '2024-01', April24 = '2024-04', Unstable = 'unstable', } ### get value: `(params: GetRequestParams) => Promise>` - GetRequestParams: export interface GetRequestParams { /** * The path to the resource, relative to the API version root. */ path: string; /** * The type of data expected in the response. */ type?: DataType; /** * The request body. */ data?: Record | string; /** * Query parameters to be sent with the request. */ query?: SearchParams; /** * Additional headers to be sent with the request. */ extraHeaders?: HeaderParams; /** * The maximum number of times the request can be made if it fails with a throttling or server error. */ tries?: number; } - RestRequestReturn: export interface RestRequestReturn { body: T; headers: Headers; pageInfo?: PageInfo; } Performs a GET request on the given path. ### post value: `(params: PostRequestParams) => Promise>` - PostRequestParams: GetRequestParams & { data: Record | string; } - RestRequestReturn: export interface RestRequestReturn { body: T; headers: Headers; pageInfo?: PageInfo; } Performs a POST request on the given path. ### put value: `(params: PostRequestParams) => Promise>` - PostRequestParams: GetRequestParams & { data: Record | string; } - RestRequestReturn: export interface RestRequestReturn { body: T; headers: Headers; pageInfo?: PageInfo; } Performs a PUT request on the given path. ### delete value: `(params: GetRequestParams) => Promise>` - GetRequestParams: export interface GetRequestParams { /** * The path to the resource, relative to the API version root. */ path: string; /** * The type of data expected in the response. */ type?: DataType; /** * The request body. */ data?: Record | string; /** * Query parameters to be sent with the request. */ query?: SearchParams; /** * Additional headers to be sent with the request. */ extraHeaders?: HeaderParams; /** * The maximum number of times the request can be made if it fails with a throttling or server error. */ tries?: number; } - RestRequestReturn: export interface RestRequestReturn { body: T; headers: Headers; pageInfo?: PageInfo; } Performs a DELETE request on the given path. ### RestRequestReturn ### body value: `T` ### headers value: `Headers` - Headers: Record ### pageInfo value: `PageInfo` - PageInfo: export interface PageInfo { limit: string; fields?: string[]; previousPageUrl?: string; nextPageUrl?: string; prevPage?: PageInfoParams; nextPage?: PageInfoParams; } ### PageInfo ### limit value: `string` ### fields value: `string[]` ### previousPageUrl value: `string` ### nextPageUrl value: `string` ### prevPage value: `PageInfoParams` - PageInfo: export interface PageInfo { limit: string; fields?: string[]; previousPageUrl?: string; nextPageUrl?: string; prevPage?: PageInfoParams; nextPage?: PageInfoParams; } - PageInfoParams: export interface PageInfoParams { path: string; query: SearchParams; } ### nextPage value: `PageInfoParams` - PageInfo: export interface PageInfo { limit: string; fields?: string[]; previousPageUrl?: string; nextPageUrl?: string; prevPage?: PageInfoParams; nextPage?: PageInfoParams; } - PageInfoParams: export interface PageInfoParams { path: string; query: SearchParams; } ### PageInfoParams ### path value: `string` ### query value: `SearchParams` ### Unauthenticated ### admin value: `GetUnauthenticatedAdminContext` - AdminContext: Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext : EmbeddedAdminContext - Unauthenticated: 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {storefront} = await shopify.unauthenticated.storefront(shop); * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` */ storefront: GetUnauthenticatedStorefrontContext; } - GetUnauthenticatedAdminContext: export type GetUnauthenticatedAdminContext< Resources extends ShopifyRestResources, > = (shop: string) => Promise>; - UnauthenticatedAdminContext: 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const shop = getShopFromExternalRequest(request); * const { session } = await unauthenticated.admin(shop); * return json(await getMyAppData({shop: session.shop)); * }; * ``` */ session: Session; /** * Methods for interacting with the GraphQL / REST Admin APIs for the given store. * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { admin, session } = await unauthenticated.admin(request); * * const response = await admin.rest.get( * { * path: "/customers/count.json" * } * ); * const customers = await response.json(); * * return json({ customers }); * }; * ``` * * ```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 unauthenticated = shopify.unauthenticated; * ``` * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await unauthenticated.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 }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * restResources, * // ...etc * }); * export default shopify; * export const unauthenticated = shopify.unauthenticated; * ``` */ admin: AdminApiContext; } 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. ### storefront value: `GetUnauthenticatedStorefrontContext` - StorefrontContext: export interface StorefrontContext { /** * Method for interacting with the Shopify Storefront GraphQL API * * If you're getting incorrect type hints in the Shopify template, follow [these instructions](https://github.com/Shopify/shopify-app-template-remix/tree/main#incorrect-graphql-hints). * * {@link https://shopify.dev/docs/api/storefront} * * @example * Querying the GraphQL API. * Use `storefront.graphql` to make query / mutation requests. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { storefront } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { storefront } = await authenticate.public.appProxy(request); * * try { * const response = await storefront.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // { errors: { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } - Unauthenticated: 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {storefront} = await shopify.unauthenticated.storefront(shop); * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` */ storefront: GetUnauthenticatedStorefrontContext; } - GetUnauthenticatedStorefrontContext: export type GetUnauthenticatedStorefrontContext = ( shop: string, ) => Promise; - UnauthenticatedStorefrontContext: export interface UnauthenticatedStorefrontContext { /** * The session for the given shop. * * This comes from the session storage which `shopifyApp` uses to store sessions in your database of choice. * * This will always be an offline session. You can use this to get shop specific data. * * @example * Using the offline session. * Get your app's shop-specific data using the returned offline `session` object. * ```ts * // app/routes/**\/.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { unauthenticated } from "../shopify.server"; * import { getMyAppData } from "~/db/model.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const shop = getShopFromExternalRequest(request); * const { session } = await unauthenticated.storefront(shop); * return json(await getMyAppData({shop: session.shop)); * }; * ``` */ session: Session; /** * Method for interacting with the Shopify GraphQL Storefront API for the given store. */ storefront: StorefrontContext; } 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. ### GetUnauthenticatedAdminContext #### Returns: Promise> #### Params: - shop: string export type GetUnauthenticatedAdminContext< Resources extends ShopifyRestResources, > = (shop: string) => Promise>; ### UnauthenticatedAdminContext ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } 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. ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Methods for interacting with the GraphQL / REST Admin APIs for the given store. ### GetUnauthenticatedStorefrontContext #### Returns: Promise #### Params: - shop: string export type GetUnauthenticatedStorefrontContext = ( shop: string, ) => Promise; ### UnauthenticatedStorefrontContext ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } 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. ### storefront value: `StorefrontContext` - StorefrontContext: export interface StorefrontContext { /** * Method for interacting with the Shopify Storefront GraphQL API * * If you're getting incorrect type hints in the Shopify template, follow [these instructions](https://github.com/Shopify/shopify-app-template-remix/tree/main#incorrect-graphql-hints). * * {@link https://shopify.dev/docs/api/storefront} * * @example * Querying the GraphQL API. * Use `storefront.graphql` to make query / mutation requests. * ```ts * // app/routes/**\/.ts * import { json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { storefront } = await authenticate.public.appProxy(request); * * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { storefront } = await authenticate.public.appProxy(request); * * try { * const response = await storefront.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // { errors: { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } Method for interacting with the Shopify GraphQL Storefront API for the given store. ### ShopifyAppBase ### sessionStorage value: `SessionStorageType` - SessionStorageType: Config['sessionStorage'] extends SessionStorage ? Config['sessionStorage'] : SessionStorage - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } The `SessionStorage` instance you passed in as a config option. ### addDocumentResponseHeaders value: `AddDocumentResponseHeaders` - AddDocumentResponseHeaders: type AddDocumentResponseHeaders = (request: Request, headers: Headers) => void; - Headers: Record Adds the required Content Security Policy headers for Shopify apps to the given Headers object. ### registerWebhooks value: `RegisterWebhooks` - RegisterWebhooks: type RegisterWebhooks = ( options: RegisterWebhooksOptions, ) => Promise; Register webhook topics for a store using the given session. Most likely you want to use this in combination with the afterAuth hook. ### authenticate value: `Authenticate` - Authenticate: interface Authenticate { /** * Authenticate an admin Request and get back an authenticated admin context. Use the authenticated admin context to interact with Shopify. * * Examples of when to use this are requests from your app's UI, or requests from admin extensions. * * If there is no session for the Request, this will redirect the merchant to correct auth flows. * * @example * Authenticating a request for an embedded app. * ```ts * // /app/routes/**\/*.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {admin, session, sessionToken, billing} = authenticate.admin(request); * * return json(await admin.rest.resources.Product.count({ session })); * } * ``` * ```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; * ``` */ admin: AuthenticateAdmin>; /** * Authenticate a Flow extension Request and get back an authenticated context, containing an admin context to access * the API, and the payload of the request. * * If there is no session for the Request, this will return an HTTP 400 error. * * Note that this will always be a POST request. * * @example * Authenticating a Flow extension request. * ```ts * // /app/routes/**\/*.jsx * import { ActionFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const {admin, session, payload} = authenticate.flow(request); * * // Perform flow extension logic * * // Return a 200 response * return null; * } * ``` * ```ts * // /app/shopify.server.ts * import { 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; * ``` */ flow: AuthenticateFlow>; /** * Authenticate a request from a fulfillment service and get back an authenticated context. * * @example * Shopify session for the fulfillment service request. * Use the session associated with this request to use the Admin GraphQL API * ```ts * // /app/routes/fulfillment_order_notification.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export async function action({ request }: ActionFunctionArgs) { * const { admin } = await authenticate.fulfillmentService(request); * * const response = await admin.graphql( * `#graphql * mutation acceptFulfillmentRequest { * fulfillmentOrderAcceptFulfillmentRequest( * id: "gid://shopify/FulfillmentOrder/5014440902678", * message: "Reminder that tomorrow is a holiday. We won't be able to ship this until Monday."){ * fulfillmentOrder { * status * requestStatus * } * } * } * ); * * const productData = await response.json(); * return json({ data: productData.data }); * } * ``` * */ fulfillmentService: AuthenticateFulfillmentService>; /** * Authenticate a public request and get back a session token. * * @example * Authenticating a request from a checkout extension * * ```ts * // /app/routes/api/checkout.jsx * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../../shopify.server"; * import { getWidgets } from "~/db/widgets"; * * export async function loader({ request }: LoaderFunctionArgs) { * const {sessionToken} = authenticate.public.checkout(request); * * return json(await getWidgets(sessionToken)); * } * ``` */ public: AuthenticatePublic; /** * Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request * * @example * Authenticating a webhook request * * ```ts * // /app/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 { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * import db from "../db.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { topic, shop, session } = 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< Config['future'], RestResourcesType, keyof Config['webhooks'] | MandatoryTopics >; } Ways to authenticate requests from different surfaces across Shopify. ### unauthenticated value: `Unauthenticated>` - RestResourcesType: Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources - Unauthenticated: 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {admin} = await shopify.unauthenticated.admin(shop); * * 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 { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticateExternal } from "~/helpers/authenticate" * import shopify from "../../shopify.server"; * * export async function loader({ request }: LoaderFunctionArgs) { * const shop = await authenticateExternal(request) * const {storefront} = await shopify.unauthenticated.storefront(shop); * const response = await storefront.graphql(`{blogs(first: 10) { edges { node { id } } } }`); * * return json(await response.json()); * } * ``` */ storefront: GetUnauthenticatedStorefrontContext; } Ways to get Contexts from requests that do not originate from Shopify. ### ShopifyAppLogin ### login value: `Login` - Login: type Login = (request: Request) => Promise; 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. ### Login #### Returns: Promise #### Params: - request: Request type Login = (request: Request) => Promise; ### LoginError ### shop value: `LoginErrorType` - Login: type Login = (request: Request) => Promise; - LoginError: export interface LoginError { shop?: LoginErrorType; } - LoginErrorType: export enum LoginErrorType { MissingShop = 'MISSING_SHOP', InvalidShop = 'INVALID_SHOP', } ### LoginErrorType ### MissingShop value: `MISSING_SHOP` ### InvalidShop value: `INVALID_SHOP` ### AppConfigArg ### appUrl value: `string` 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. ### sessionStorage value: `Storage` An adaptor for storing sessions in your database of choice. Shopify provides multiple session storage adaptors and you can create your own. ### useOnlineTokens value: `boolean` 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. ### webhooks value: `WebhookConfig` - WebhookConfig: Record 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. ### hooks value: `HooksConfig` - HooksConfig: 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; } 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. ### isEmbeddedApp value: `boolean` Does your app render embedded inside the Shopify Admin or on its own. Unless you have very specific needs, this should be true. ### distribution value: `AppDistribution` - AppDistribution: export enum AppDistribution { AppStore = 'app_store', SingleMerchant = 'single_merchant', ShopifyAdmin = 'shopify_admin', } How your app is distributed. Default is `AppDistribution.AppStore`. ### apiVersion value: `ApiVersion` - ApiVersion: export enum ApiVersion { October22 = '2022-10', January23 = '2023-01', April23 = '2023-04', July23 = '2023-07', October23 = '2023-10', January24 = '2024-01', April24 = '2024-04', Unstable = 'unstable', } What version of Shopify's Admin API's would you like to use. ### authPathPrefix value: `string` 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)`. ### future value: `Future` Features that will be introduced in future releases of this package. You can opt in to these features by setting the corresponding flags. By doing so, you can prepare for future releases in advance and provide feedback on the new features. ### apiKey value: `string` The API key for your app. Also known as Client ID in your Partner Dashboard. ### apiSecretKey value: `string` The API secret key for your app. Also known as Client Secret in your Partner Dashboard. ### scopes value: `string[] | AuthScopes` - AuthScopes: class AuthScopes { public static SCOPE_DELIMITER = ','; private compressedScopes: Set; private expandedScopes: Set; constructor(scopes: string | string[] | AuthScopes | undefined) { let scopesArray: string[] = []; if (typeof scopes === 'string') { scopesArray = scopes.split( new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`), ); } else if (Array.isArray(scopes)) { scopesArray = scopes; } else if (scopes) { scopesArray = Array.from(scopes.expandedScopes); } scopesArray = scopesArray .map((scope) => scope.trim()) .filter((scope) => scope.length); const impliedScopes = this.getImpliedScopes(scopesArray); const scopeSet = new Set(scopesArray); const impliedSet = new Set(impliedScopes); this.compressedScopes = new Set( [...scopeSet].filter((x) => !impliedSet.has(x)), ); this.expandedScopes = new Set([...scopeSet, ...impliedSet]); } /** * Checks whether the current set of scopes includes the given one. */ public has(scope: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (scope instanceof AuthScopes) { other = scope; } else { other = new AuthScopes(scope); } return ( other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0 ); } /** * Checks whether the current set of scopes equals the given one. */ public equals(otherScopes: string | string[] | AuthScopes | undefined) { let other: AuthScopes; if (otherScopes instanceof AuthScopes) { other = otherScopes; } else { other = new AuthScopes(otherScopes); } return ( this.compressedScopes.size === other.compressedScopes.size && this.toArray().filter((x) => !other.has(x)).length === 0 ); } /** * Returns a comma-separated string with the current set of scopes. */ public toString() { return this.toArray().join(AuthScopes.SCOPE_DELIMITER); } /** * Returns an array with the current set of scopes. */ public toArray() { return [...this.compressedScopes]; } private getImpliedScopes(scopesArray: string[]): string[] { return scopesArray.reduce((array: string[], current: string) => { const matches = current.match(/^(unauthenticated_)?write_(.*)$/); if (matches) { array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`); } return array; }, []); } } The scopes your app needs to access the API. ### adminApiAccessToken value: `string` An app-wide API access token. Only applies to custom apps. ### userAgentPrefix value: `string` The user agent prefix to use for API requests. ### privateAppStorefrontAccessToken value: `string` An app-wide API access token for the storefront API. Only applies to custom apps. ### customShopDomains value: `(string | RegExp)[]` Override values for Shopify shop domains. ### billing value: `BillingConfig` - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } Billing configurations for the app. ### restResources value: `Resources` REST resources to access the Admin API. You can import these from `@shopify/shopify-api/rest/admin/*`. ### logger value: `{ log?: LogFunction; level?: LogSeverity; httpRequests?: boolean; timestamps?: boolean; }` - LogFunction: export type LogFunction = (severity: LogSeverity, msg: string) => void; - LogSeverity: export enum LogSeverity { Error, Warning, Info, Debug, } Customization options for Shopify logs. ### _logDisabledFutureFlags value: `boolean` Whether to log disabled future flags at startup. ### HooksConfig ### afterAuth value: `(options: AfterAuthOptions) => void | Promise` - ShopifyRestResources: Record - Options: interface Options { /** * Whether to use the shop's theme layout around the Liquid content. */ layout?: boolean; } - AfterAuthOptions: export interface AfterAuthOptions< R extends ShopifyRestResources = ShopifyRestResources, > { session: Session; admin: AdminApiContext; } A function to call after a merchant installs your app ### AfterAuthOptions ### session value: `Session` - Session: export class Session { public static fromPropertyArray( entries: [string, string | number | boolean][], returnUserData = false, ): Session { if (!Array.isArray(entries)) { throw new InvalidSession( 'The parameter is not an array: a Session cannot be created from this object.', ); } const obj = Object.fromEntries( entries .filter(([_key, value]) => value !== null && value !== undefined) // Sanitize keys .map(([key, value]) => { switch (key.toLowerCase()) { case 'isonline': return ['isOnline', value]; case 'accesstoken': return ['accessToken', value]; case 'onlineaccessinfo': return ['onlineAccessInfo', value]; case 'userid': return ['userId', value]; case 'firstname': return ['firstName', value]; case 'lastname': return ['lastName', value]; case 'accountowner': return ['accountOwner', value]; case 'emailverified': return ['emailVerified', value]; default: return [key.toLowerCase(), value]; } }), ); const sessionData = {} as SessionParams; const onlineAccessInfo = { associated_user: {}, } as OnlineAccessInfo; Object.entries(obj).forEach(([key, value]) => { switch (key) { case 'isOnline': if (typeof value === 'string') { sessionData[key] = value.toString().toLowerCase() === 'true'; } else if (typeof value === 'number') { sessionData[key] = Boolean(value); } else { sessionData[key] = value; } break; case 'scope': sessionData[key] = value.toString(); break; case 'expires': sessionData[key] = value ? new Date(Number(value)) : undefined; break; case 'onlineAccessInfo': onlineAccessInfo.associated_user.id = Number(value); break; case 'userId': if (returnUserData) { onlineAccessInfo.associated_user.id = Number(value); break; } case 'firstName': if (returnUserData) { onlineAccessInfo.associated_user.first_name = String(value); break; } case 'lastName': if (returnUserData) { onlineAccessInfo.associated_user.last_name = String(value); break; } case 'email': if (returnUserData) { onlineAccessInfo.associated_user.email = String(value); break; } case 'accountOwner': if (returnUserData) { onlineAccessInfo.associated_user.account_owner = Boolean(value); break; } case 'locale': if (returnUserData) { onlineAccessInfo.associated_user.locale = String(value); break; } case 'collaborator': if (returnUserData) { onlineAccessInfo.associated_user.collaborator = Boolean(value); break; } case 'emailVerified': if (returnUserData) { onlineAccessInfo.associated_user.email_verified = Boolean(value); break; } // Return any user keys as passed in default: sessionData[key] = value; } }); if (sessionData.isOnline) { sessionData.onlineAccessInfo = onlineAccessInfo; } const session = new Session(sessionData); return session; } /** * The unique identifier for the session. */ readonly id: string; /** * The Shopify shop domain, such as `example.myshopify.com`. */ public shop: string; /** * The state of the session. Used for the OAuth authentication code flow. */ public state: string; /** * Whether the access token in the session is online or offline. */ public isOnline: boolean; /** * The desired scopes for the access token, at the time the session was created. */ public scope?: string; /** * The date the access token expires. */ public expires?: Date; /** * The access token for the session. */ public accessToken?: string; /** * Information on the user for the session. Only present for online sessions. */ public onlineAccessInfo?: OnlineAccessInfo; constructor(params: SessionParams) { Object.assign(this, params); } /** * Whether the session is active. Active sessions have an access token that is not expired, and has the given scopes. */ public isActive(scopes: AuthScopes | string | string[]): boolean { return ( !this.isScopeChanged(scopes) && Boolean(this.accessToken) && !this.isExpired() ); } /** * Whether the access token has the given scopes. */ public isScopeChanged(scopes: AuthScopes | string | string[]): boolean { const scopesObject = scopes instanceof AuthScopes ? scopes : new AuthScopes(scopes); return !scopesObject.equals(this.scope); } /** * Whether the access token is expired. */ public isExpired(withinMillisecondsOfExpiry = 0): boolean { return Boolean( this.expires && this.expires.getTime() - withinMillisecondsOfExpiry < Date.now(), ); } /** * Converts an object with data into a Session. */ public toObject(): SessionParams { const object: SessionParams = { id: this.id, shop: this.shop, state: this.state, isOnline: this.isOnline, }; if (this.scope) { object.scope = this.scope; } if (this.expires) { object.expires = this.expires; } if (this.accessToken) { object.accessToken = this.accessToken; } if (this.onlineAccessInfo) { object.onlineAccessInfo = this.onlineAccessInfo; } return object; } /** * Checks whether the given session is equal to this session. */ public equals(other: Session | undefined): boolean { if (!other) return false; const mandatoryPropsMatch = this.id === other.id && this.shop === other.shop && this.state === other.state && this.isOnline === other.isOnline; if (!mandatoryPropsMatch) return false; const copyA = this.toPropertyArray(true); copyA.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); const copyB = other.toPropertyArray(true); copyB.sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)); return JSON.stringify(copyA) === JSON.stringify(copyB); } /** * Converts the session into an array of key-value pairs. */ public toPropertyArray( returnUserData = false, ): [string, string | number | boolean][] { return ( Object.entries(this) .filter( ([key, value]) => propertiesToSave.includes(key) && value !== undefined && value !== null, ) // Prepare values for db storage .flatMap(([key, value]): [string, string | number | boolean][] => { switch (key) { case 'expires': return [[key, value ? value.getTime() : undefined]]; case 'onlineAccessInfo': // eslint-disable-next-line no-negated-condition if (!returnUserData) { return [[key, value.associated_user.id]]; } else { return [ ['userId', value?.associated_user?.id], ['firstName', value?.associated_user?.first_name], ['lastName', value?.associated_user?.last_name], ['email', value?.associated_user?.email], ['locale', value?.associated_user?.locale], ['emailVerified', value?.associated_user?.email_verified], ['accountOwner', value?.associated_user?.account_owner], ['collaborator', value?.associated_user?.collaborator], ]; } default: return [[key, value]]; } }) // Filter out tuples with undefined values .filter(([_key, value]) => value !== undefined) ); } } ### admin value: `AdminApiContext` - AdminApiContext: 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. Visit the [Admin REST API references](https://shopify.dev/docs/api/admin-rest) for examples on using each resource. * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * return json( * admin.rest.resources.Order.count({ session }), * ); * }; * ``` * * ```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; * ``` * * @example * Performing a GET request to the REST API. * Use `admin.rest.get` to make custom requests to make a request to to the `customer/count` endpoint * * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * 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 }); * }; * ``` * * ```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; * ``` * * @example * Performing a POST request to the REST API. * Use `admin.rest.post` to make custom requests to make a request to to the `customers.json` endpoint to send a welcome email * ```ts * // /app/routes/**\/*.ts * import { LoaderFunctionArgs, json } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const loader = async ({ request }: LoaderFunctionArgs) => { * const { * admin, * session, * } = await authenticate.admin(request); * * const response = admin.rest.post({ * path: "customers/7392136888625/send_invite.json", * body: { * customer_invite: { * to: "new_test_email@shopify.com", * from: "j.limited@example.com", * bcc: ["j.limited@example.com"], * subject: "Welcome to my new shop", * custom_message: "My awesome new store", * }, * }, * }); * * const customerInvite = await response.json(); * return json({ customerInvite }); * }; * ``` * * ```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; * ``` */ 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-app-js/blob/main/packages/apps/shopify-api/docs/reference/clients/Graphql.md} * * @example * Querying the GraphQL API. * Use `admin.graphql` to make query / mutation requests. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * const response = await admin.graphql( * `#graphql * mutation populateProduct($input: ProductInput!) { * productCreate(input: $input) { * product { * id * } * } * }`, * { * variables: { * input: { title: "Product Name" }, * }, * }, * ); * * const productData = await response.json(); * return json({ * productId: productData.data?.productCreate?.product?.id, * }); * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` * * @example * Handling GraphQL errors. * Catch `GraphqlQueryError` errors to see error messages from the API. * ```ts * // /app/routes/**\/*.ts * import { ActionFunctionArgs } from "@remix-run/node"; * import { authenticate } from "../shopify.server"; * * export const action = async ({ request }: ActionFunctionArgs) => { * const { admin } = await authenticate.admin(request); * * try { * const response = await admin.graphql( * `#graphql * query incorrectQuery { * products(first: 10) { * nodes { * not_a_field * } * } * }`, * ); * * return json({ data: await response.json() }); * } catch (error) { * if (error instanceof GraphqlQueryError) { * // error.body.errors: * // { graphQLErrors: [ * // { message: "Field 'not_a_field' doesn't exist on type 'Product'" } * // ] } * return json({ errors: error.body?.errors }, { status: 500 }); * } * return json({ message: "An error occurred" }, { status: 500 }); * } * } * ``` * * ```ts * // /app/shopify.server.ts * import { shopifyApp } from "@shopify/shopify-app-remix/server"; * * const shopify = shopifyApp({ * // ... * }); * export default shopify; * export const authenticate = shopify.authenticate; * ``` */ graphql: GraphQLClient; } ### BillingConfig Billing configuration options, indexed by an app-specific plan name. ### [plan: string] value: `BillingConfigItem` - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } - BillingConfigItem: FeatureEnabled extends true ? BillingConfigOneTimePlan | BillingConfigSubscriptionLineItemPlan : BillingConfigLegacyItem ### BillingConfigOneTimePlan ### interval value: `BillingInterval.OneTime` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } Interval for this plan. Must be set to `OneTime`. ### amount value: `number` Amount to charge for this plan. ### currencyCode value: `string` Currency code for this plan. ### BillingConfigSubscriptionLineItemPlan ### replacementBehavior value: `BillingReplacementBehavior` - BillingReplacementBehavior: export enum BillingReplacementBehavior { ApplyImmediately = 'APPLY_IMMEDIATELY', ApplyOnNextBillingCycle = 'APPLY_ON_NEXT_BILLING_CYCLE', Standard = 'STANDARD', } The replacement behavior to use for this plan. ### trialDays value: `number` How many trial days to give before charging for this plan. ### lineItems value: `(BillingConfigRecurringLineItem | BillingConfigUsageLineItem)[]` - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } - BillingConfigRecurringLineItem: export interface BillingConfigRecurringLineItem extends BillingConfigLineItem { /** * The recurring interval for this line item. * * Must be either `Every30Days` or `Annual`. */ interval: BillingInterval.Every30Days | BillingInterval.Annual; /** * An optional discount to apply for this line item. */ discount?: BillingConfigSubscriptionPlanDiscount; } - BillingConfigUsageLineItem: export interface BillingConfigUsageLineItem extends BillingConfigLineItem { /** * The usage interval for this line item. * * Must be set to `Usage`. */ interval: BillingInterval.Usage; /** * Usage terms for this line item. */ terms: string; } The line items for this plan. ### BillingReplacementBehavior ### ApplyImmediately value: `APPLY_IMMEDIATELY` ### ApplyOnNextBillingCycle value: `APPLY_ON_NEXT_BILLING_CYCLE` ### Standard value: `STANDARD` ### BillingConfigRecurringLineItem ### interval value: `BillingInterval.Every30Days | BillingInterval.Annual` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } The recurring interval for this line item. Must be either `Every30Days` or `Annual`. ### discount value: `BillingConfigSubscriptionPlanDiscount` - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } - BillingConfigSubscriptionPlanDiscount: export interface BillingConfigSubscriptionPlanDiscount { /** * The number of intervals to apply the discount for. */ durationLimitInIntervals?: number; /** * The discount to apply. */ value: | BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage; } - BillingConfigSubscriptionPlan: export interface BillingConfigSubscriptionPlan extends BillingConfigPlan { /** * Recurring interval for this plan. * * Must be either `Every30Days` or `Annual`. */ interval: Exclude; /** * How many trial days to give before charging for this plan. */ trialDays?: number; /** * The behavior to use when replacing an existing subscription with a new one. */ replacementBehavior?: BillingReplacementBehavior; /** * The discount to apply to this plan. */ discount?: BillingConfigSubscriptionPlanDiscount; } An optional discount to apply for this line item. ### amount value: `number` The amount to charge for this line item. ### currencyCode value: `string` The currency code for this line item. ### BillingConfigSubscriptionPlanDiscount ### durationLimitInIntervals value: `number` The number of intervals to apply the discount for. ### value value: `BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage` - BillingConfigSubscriptionPlanDiscountAmount: export interface BillingConfigSubscriptionPlanDiscountAmount { /** * The amount to discount. * * Cannot be set if `percentage` is set. */ amount: number; /** * The percentage to discount. * * Cannot be set if `amount` is set. */ percentage?: never; } - BillingConfigSubscriptionPlanDiscountPercentage: export interface BillingConfigSubscriptionPlanDiscountPercentage { /** * The amount to discount. * * Cannot be set if `percentage` is set. */ amount?: never; /** * The percentage to discount. * * Cannot be set if `amount` is set. */ percentage: number; } - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } - BillingConfigSubscriptionPlanDiscount: export interface BillingConfigSubscriptionPlanDiscount { /** * The number of intervals to apply the discount for. */ durationLimitInIntervals?: number; /** * The discount to apply. */ value: | BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage; } - BillingConfigSubscriptionPlan: export interface BillingConfigSubscriptionPlan extends BillingConfigPlan { /** * Recurring interval for this plan. * * Must be either `Every30Days` or `Annual`. */ interval: Exclude; /** * How many trial days to give before charging for this plan. */ trialDays?: number; /** * The behavior to use when replacing an existing subscription with a new one. */ replacementBehavior?: BillingReplacementBehavior; /** * The discount to apply to this plan. */ discount?: BillingConfigSubscriptionPlanDiscount; } The discount to apply. ### BillingConfigUsageLineItem ### interval value: `BillingInterval.Usage` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } The usage interval for this line item. Must be set to `Usage`. ### terms value: `string` Usage terms for this line item. ### amount value: `number` The amount to charge for this line item. ### currencyCode value: `string` The currency code for this line item. ### BillingConfigSubscriptionPlan ### interval value: `Exclude` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } - RecurringBillingIntervals: RecurringBillingIntervals Recurring interval for this plan. Must be either `Every30Days` or `Annual`. ### trialDays value: `number` How many trial days to give before charging for this plan. ### replacementBehavior value: `BillingReplacementBehavior` - BillingReplacementBehavior: export enum BillingReplacementBehavior { ApplyImmediately = 'APPLY_IMMEDIATELY', ApplyOnNextBillingCycle = 'APPLY_ON_NEXT_BILLING_CYCLE', Standard = 'STANDARD', } The behavior to use when replacing an existing subscription with a new one. ### discount value: `BillingConfigSubscriptionPlanDiscount` - BillingConfig: export interface BillingConfig< Future extends FutureFlagOptions = FutureFlagOptions, > { /** * An individual billing plan. */ [plan: string]: BillingConfigItem; } - BillingConfigSubscriptionPlanDiscount: export interface BillingConfigSubscriptionPlanDiscount { /** * The number of intervals to apply the discount for. */ durationLimitInIntervals?: number; /** * The discount to apply. */ value: | BillingConfigSubscriptionPlanDiscountAmount | BillingConfigSubscriptionPlanDiscountPercentage; } - BillingConfigSubscriptionPlan: export interface BillingConfigSubscriptionPlan extends BillingConfigPlan { /** * Recurring interval for this plan. * * Must be either `Every30Days` or `Annual`. */ interval: Exclude; /** * How many trial days to give before charging for this plan. */ trialDays?: number; /** * The behavior to use when replacing an existing subscription with a new one. */ replacementBehavior?: BillingReplacementBehavior; /** * The discount to apply to this plan. */ discount?: BillingConfigSubscriptionPlanDiscount; } The discount to apply to this plan. ### amount value: `number` Amount to charge for this plan. ### currencyCode value: `string` Currency code for this plan. ### BillingConfigUsagePlan ### interval value: `BillingInterval.Usage` - BillingInterval: export enum BillingInterval { OneTime = 'ONE_TIME', Every30Days = 'EVERY_30_DAYS', Annual = 'ANNUAL', Usage = 'USAGE', } Interval for this plan. Must be set to `Usage`. ### usageTerms value: `string` Usage terms for this plan. ### trialDays value: `number` How many trial days to give before charging for this plan. ### replacementBehavior value: `BillingReplacementBehavior` - BillingReplacementBehavior: export enum BillingReplacementBehavior { ApplyImmediately = 'APPLY_IMMEDIATELY', ApplyOnNextBillingCycle = 'APPLY_ON_NEXT_BILLING_CYCLE', Standard = 'STANDARD', } The behavior to use when replacing an existing subscription with a new one. ### amount value: `number` Amount to charge for this plan. ### currencyCode value: `string` Currency code for this plan. ### LogFunction A function used by the library to log events related to Shopify. #### Returns: void #### Params: - severity: LogSeverity - msg: string export type LogFunction = (severity: LogSeverity, msg: string) => void; ### LogSeverity ### Error value: `0` ### Warning value: `1` ### Info value: `2` ### Debug value: `3` ## Related - [Authenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/authenticate) - [Unauthenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/unauthenticated) ## Examples 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. ### sessionStorage Import the `@shopify/shopify-app-session-storage-prisma` package to store sessions in your Prisma database.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; import prisma from "~/db.server"; const shopify = shopifyApp({ sessionStorage: new PrismaSessionStorage(prisma), // ...etc }) // shopify.sessionStorage is an instance of PrismaSessionStorage ``` ### addDocumentResponseHeaders Add headers to all HTML requests by calling `shopify.addDocumentResponseHeaders` in `entry.server.tsx`.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; ``` ```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, }); } ``` ### registerWebhooks Trigger the registration to create the webhook subscriptions after a merchant installs your app using the `afterAuth` hook. Learn more about [subscribing to webhooks.](https://shopify.dev/docs/api/shopify-app-remix/v1/guide-webhooks)```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 Use the functions in `authenticate` to validate requests coming from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); return json(await admin.rest.resources.Product.count({ session })); } ``` ### unauthenticated Create contexts for requests that don't come from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import { authenticateExternal } from "~/helpers/authenticate" import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const shop = await authenticateExternal(request) const {admin} = await shopify.unauthenticated.admin(shop); return json(await admin.rest.resources.Product.count({ session })); } ``` ### login Use `shopify.login` to create a login form, in a route that can handle GET and POST requests.```typescript import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ```typescript import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const errors = shopify.login(request); return json(errors); } export async function action({ request }: ActionFunctionArgs) { const errors = shopify.login(request); return json(errors); } export default function Auth() { const actionData = useActionData(); const [shop, setShop] = useState(""); return (
Login
); } ``` ## Future flags Set future flags using the `future` configuration field to opt in to upcoming breaking changes. With this feature, you can prepare for major releases ahead of time, as well as try out new features before they are released. ### FutureFlags ### v3_webhookAdminContext value: `boolean` When enabled, returns the same `admin` context (`AdminApiContext`) from `authenticate.webhook` that is returned from `authenticate.admin`. ### v3_authenticatePublic value: `boolean` When enabled authenticate.public() will not work. Use authenticate.public.checkout() instead. ### v3_lineItemBilling value: `boolean` When enabled allows you to pass billing plans with line items when creating a new app subscriptions. ### unstable_newEmbeddedAuthStrategy value: `boolean` When enabled, embedded apps will fetch access tokens via [token exchange](https://shopify.dev/docs/apps/auth/get-access-tokens/token-exchange). This assumes the app has scopes declared for [Shopify managing installation](https://shopify.dev/docs/apps/auth/installation#shopify-managed-installation). Learn more about this [new embedded app auth strategy](https://shopify.dev/docs/api/shopify-app-remix#embedded-auth-strategy). ## Related - [Authenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/authenticate) - [Unauthenticated contexts](https://shopify.dev/docs/api/shopify-app-remix/unauthenticated) ## Examples 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. ### sessionStorage Import the `@shopify/shopify-app-session-storage-prisma` package to store sessions in your Prisma database.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; import prisma from "~/db.server"; const shopify = shopifyApp({ sessionStorage: new PrismaSessionStorage(prisma), // ...etc }) // shopify.sessionStorage is an instance of PrismaSessionStorage ``` ### addDocumentResponseHeaders Add headers to all HTML requests by calling `shopify.addDocumentResponseHeaders` in `entry.server.tsx`.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; ``` ```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, }); } ``` ### registerWebhooks Trigger the registration to create the webhook subscriptions after a merchant installs your app using the `afterAuth` hook. Learn more about [subscribing to webhooks.](https://shopify.dev/docs/api/shopify-app-remix/v1/guide-webhooks)```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 Use the functions in `authenticate` to validate requests coming from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); return json(await admin.rest.resources.Product.count({ session })); } ``` ### unauthenticated Create contexts for requests that don't come from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import { authenticateExternal } from "~/helpers/authenticate" import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const shop = await authenticateExternal(request) const {admin} = await shopify.unauthenticated.admin(shop); return json(await admin.rest.resources.Product.count({ session })); } ``` ### login Use `shopify.login` to create a login form, in a route that can handle GET and POST requests.```typescript import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ```typescript import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const errors = shopify.login(request); return json(errors); } export async function action({ request }: ActionFunctionArgs) { const errors = shopify.login(request); return json(errors); } export default function Auth() { const actionData = useActionData(); const [shop, setShop] = useState(""); return (
Login
); } ``` ## Examples 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. ### sessionStorage Import the `@shopify/shopify-app-session-storage-prisma` package to store sessions in your Prisma database.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; import prisma from "~/db.server"; const shopify = shopifyApp({ sessionStorage: new PrismaSessionStorage(prisma), // ...etc }) // shopify.sessionStorage is an instance of PrismaSessionStorage ``` ### addDocumentResponseHeaders Add headers to all HTML requests by calling `shopify.addDocumentResponseHeaders` in `entry.server.tsx`.```typescript import { shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; export const addDocumentResponseheaders = shopify.addDocumentResponseheaders; ``` ```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, }); } ``` ### registerWebhooks Trigger the registration to create the webhook subscriptions after a merchant installs your app using the `afterAuth` hook. Learn more about [subscribing to webhooks.](https://shopify.dev/docs/api/shopify-app-remix/v1/guide-webhooks)```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 Use the functions in `authenticate` to validate requests coming from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const {admin, session, sessionToken, billing} = shopify.authenticate.admin(request); return json(await admin.rest.resources.Product.count({ session })); } ``` ### unauthenticated Create contexts for requests that don't come from Shopify.```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; ``` ```typescript import { LoaderFunctionArgs, json } from "@remix-run/node"; import { authenticateExternal } from "~/helpers/authenticate" import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const shop = await authenticateExternal(request) const {admin} = await shopify.unauthenticated.admin(shop); return json(await admin.rest.resources.Product.count({ session })); } ``` ### login Use `shopify.login` to create a login form, in a route that can handle GET and POST requests.```typescript import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server"; const shopify = shopifyApp({ // ...etc }); export default shopify; ``` ```typescript import shopify from "../../shopify.server"; export async function loader({ request }: LoaderFunctionArgs) { const errors = shopify.login(request); return json(errors); } export async function action({ request }: ActionFunctionArgs) { const errors = shopify.login(request); return json(errors); } export default function Auth() { const actionData = useActionData(); const [shop, setShop] = useState(""); return (
Login
); } ```