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