Returns a set of functions that can be used by the app's backend to be able to respond to all Shopify requests. The shape of the returned object changes depending on the value of `distribution`. If it is `AppDistribution.ShopifyAdmin`, then only `ShopifyAppBase` objects are returned, otherwise `ShopifyAppLogin` objects are included.
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;
Function to create a new Shopify API object.
Creates an object your app will use to interact with Shopify.
`ShopifyApp` An object constructed using your appConfig. It has methods for interacting with Shopify.
appConfig: Readonly<Config>
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>; }
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>>
Adds the required Content Security Policy headers for Shopify apps to the given Headers object.
Ways to authenticate requests from different surfaces across Shopify.
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.
The `SessionStorage` instance you passed in as a config option.
Ways to get Contexts from requests that do not originate from Shopify.
request: Request
headers: Headers
type AddDocumentResponseHeaders = (request: Request, headers: Headers) => void;
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.
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.
Authenticate a request from a fulfillment service and get back an authenticated context.
Authenticate a public request and get back a session token.
Authenticate a Shopify webhook request, get back an authenticated admin context and details on the webhook request
request: Request
export type AuthenticateAdmin< Config extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise<AdminContext<Config, Resources>>;
EmbeddedTypedAdminContext<Config, Resources> & ScopesContext
Config['isEmbeddedApp'] extends false ? NonEmbeddedAdminContext<Config, Resources> : EmbeddedAdminContext<Config, Resources>
Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request.
Billing methods for this store, based on the plans defined in the `billing` config option.
A function that ensures the CORS headers are set correctly for the response.
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.
Cancels an ongoing subscription, given its ID.
Checks if the shop has an active payment for any plan defined in the `billing` config option.
Creates a usage record for an app subscription.
Requests payment for the plan.
Checks if the shop has an active payment for any plan defined in the `billing` config option.
Updates the capped amount for a usage billing plan.
Whether to use the test mode. This prevents the credit card from being charged.
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.
The ID of the subscription to cancel.
Whether to include charges that were created on test mode. Test shops and demo shops cannot be charged.
The plans to check for. Must be one of the values defined in the `billing` config option.
The description of the app usage record.
Whether to use the test mode. This prevents the credit card from being charged.
The price of the app usage record.
Whether to use the test mode. This prevents the credit card from being charged. Test shops and demo shops cannot be charged.
The plan to request. Must be one of the values defined in the `billing` config option.
The URL to return to after the merchant approves the payment.
Whether to include charges that were created on test mode. Test shops and demo shops cannot be charged.
How to handle the request if the shop doesn't have an active payment for any plan.
The plans to check for. Must be one of the values defined in the `billing` config option.
The maximum charge for the usage billing plan.
The subscription line item ID to update.
export interface EnsureCORSFunction { (response: Response): Response; }
Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request.
Billing methods for this store, based on the plans defined in the `billing` config option.
A function that ensures the CORS headers are set correctly for the response.
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`.
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.
The decoded and validated session token for the request. Returned only if `isEmbeddedApp` is `true`.
url: string
init: RedirectInit
export type RedirectFunction = ( url: string, init?: RedirectInit, ) => TypedResponse<never>;
number | (ResponseInit & {target?: RedirectTarget})
'_self' | '_parent' | '_top' | '_blank'
Methods to manage scopes for the store that made the request.
The Scopes API enables embedded apps and extensions to request merchant consent for access scopes.
Queries Shopify for the scopes for this app on this shop
Requests the merchant to grant the provided scopes for this app on this shop Warning: This method performs a server-side redirect.
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.
The scopes that have been granted on the shop for this app
The optional scopes that the app has declared in its configuration
The required scopes that the app has declared in its configuration
The scopes that have been revoked on the shop for this app
Config['restResources'] extends ShopifyRestResources ? Config['restResources'] : ShopifyRestResources
request: Request
export type AuthenticateFlow< ConfigArg extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = (request: Request) => Promise<FlowContext<ConfigArg, Resources>>;
An admin context for the Flow request. Returned only if there is a session for the shop.
The payload from the Flow request.
A session with an offline token for the shop. Returned only if there is a session for the shop.
request: Request
export type AuthenticateFulfillmentService< ConfigArg extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = ( request: Request, ) => Promise<FulfillmentServiceContext<ConfigArg, Resources>>;
An admin context for the fulfillment service request. Returned only if there is a session for the shop.
The payload from the fulfillment service request.
A session with an offline token for the shop. Returned only if there is a session for the shop.
Record<string, any> & { kind: string; }
Authenticate a request from an app proxy
Authenticate a request from a checkout extension
Authenticate a request from a customer account extension
request: Request
export type AuthenticateAppProxy< ConfigArg extends AppConfigArg, Resources extends ShopifyRestResources = ShopifyRestResources, > = ( request: Request, ) => Promise< AppProxyContext | AppProxyContextWithSession<ConfigArg, Resources> >;
No session is available for the shop that made this request. Therefore no methods for interacting with the GraphQL / REST Admin APIs are available.
A utility for creating a Liquid Response.
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.
No session is available for the shop that made this request. Therefore no method for interacting with the Storefront API is available.
body: string
initAndOptions: number | (ResponseInit & Options)
export type LiquidResponseFunction = ( body: string, initAndOptions?: number | (ResponseInit & Options), ) => Response;
Whether to use the shop's theme layout around the Liquid content.
Methods for interacting with the GraphQL / REST Admin APIs for the store that made the request.
A utility for creating a Liquid Response.
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.
Method for interacting with the Shopify Storefront Graphql API for the store that made the request.
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).
query: Operation extends keyof Operations
options: GraphQLQueryOptions<Operation, Operations>
export type GraphQLClient<Operations extends AllOperations> = < Operation extends keyof Operations, >( query: Operation, options?: GraphQLQueryOptions<Operation, Operations>, ) => Promise<GraphQLResponse<Operation, Operations>>;
The version of the API to use for the request.
Additional headers to include in the request.
The total number of times to try the request if it fails.
The variables to pass to the operation.
request: Request
options: AuthenticateCheckoutOptions
export type AuthenticateCheckout = ( request: Request, options?: AuthenticateCheckoutOptions, ) => Promise<CheckoutContext>;
Authenticated Context for a checkout request
A function that ensures the CORS headers are set correctly for the response.
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).
request: Request
options: AuthenticateCustomerAccountOptions
export type AuthenticateCustomerAccount = ( request: Request, options?: AuthenticateCustomerAccountOptions, ) => Promise<CustomerAccountContext>;
Authenticated Context for a customer account extension request
A function that ensures the CORS headers are set correctly for the response.
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).
request: Request
export type AuthenticateWebhook< ConfigArg extends AppConfigArg, Resources extends ShopifyRestResources, Topics = string | number | symbol, > = (request: Request) => Promise<WebhookContext<ConfigArg, Resources, Topics>>;
WebhookContextWithoutSession<Topics> | WebhookContextWithSession<ConfigArg, Resources, Topics>
The API version used for the webhook.
The payload from the webhook request.
The shop where the webhook was triggered.
The sub-topic of the webhook. This is only available for certain webhooks.
The topic of the webhook.
A unique ID for the webhook. Useful to keep track of which events your app has already processed.
An admin context for the webhook. Returned only if there is a session for the shop.
The API version used for the webhook.
The payload from the webhook request.
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.
The shop where the webhook was triggered.
The sub-topic of the webhook. This is only available for certain webhooks.
The topic of the webhook.
A unique ID for the webhook. Useful to keep track of which events your app has already processed.
options: RegisterWebhooksOptions
type RegisterWebhooks = ( options: RegisterWebhooksOptions, ) => Promise<RegisterReturn | void>;
The Shopify session used to register webhooks using the Admin API.
Config['sessionStorage'] extends SessionStorage ? Config['sessionStorage'] : SessionStorage
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.
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.
shop: string
export type GetUnauthenticatedAdminContext< ConfigArg extends AppConfigArg, Resources extends ShopifyRestResources, > = ( shop: string, ) => Promise<UnauthenticatedAdminContext<ConfigArg, Resources>>;
Methods for interacting with the GraphQL / REST Admin APIs for the given store.
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.
shop: string
export type GetUnauthenticatedStorefrontContext = ( shop: string, ) => Promise<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.
Method for interacting with the Shopify GraphQL Storefront API for the given store.
Base & { sessionStorage: SessionStorageType<Config>; }
Stores App information from logged in merchants so they can make authenticated requests to the Admin API.
The unique identifier for the session.
The Shopify shop domain, such as `example.myshopify.com`.
The state of the session. Used for the OAuth authentication code flow.
Whether the access token in the session is online or offline.
The desired scopes for the access token, at the time the session was created.
The date the access token expires.
The access token for the session.
Information on the user for the session. Only present for online sessions.
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.
Whether the access token includes the given scopes if they are provided.
Whether the access token includes the given scopes.
Whether the access token is expired.
Converts an object with data into a Session.
Checks whether the given session is equal to this session.
Converts the session into an array of key-value pairs.
The user associated with the access token.
The effective set of scopes for the session.
How long the access token is valid for, in seconds.
Whether the user is the account owner.
Whether the user is a collaborator.
The user's email address.
Whether the user has verified their email address.
The user's first name.
The user's ID.
The user's last name.
The user's locale.
A class that represents a set of access token scopes.
Checks whether the current set of scopes includes the given one.
Checks whether the current set of scopes equals the given one.
Returns a comma-separated string with the current set of scopes.
Returns an array with the current set of scopes.
The access token for the session.
The date the access token expires.
The unique identifier for the session.
Whether the access token in the session is online or offline.
Information on the user for the session. Only present for online sessions.
The scopes for the access token.
The Shopify shop domain.
The state of the session. Used for the OAuth authentication code flow.
Omit<OnlineAccessInfo, 'associated_user'> & { associated_user: Partial<OnlineAccessUser>; }
Record<string, any>
Record<string, any>
Record<string, string | number | null>
ShopifyAppBase<Config> & ShopifyAppLogin
Adds the required Content Security Policy headers for Shopify apps to the given Headers object.
Ways to authenticate requests from different surfaces across Shopify.
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.
The `SessionStorage` instance you passed in as a config option.
Ways to get Contexts from requests that do not originate from Shopify.
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.
request: Request
type Login = (request: Request) => Promise<LoginError | never>;
ShopifyAppBase<Config> & ShopifyAppLogin
Whether to log disabled future flags at startup.
An app-wide API access token. Only applies to custom apps.
The API key for your app. Also known as Client ID in your Partner Dashboard.
The API secret key for your app. Also known as Client Secret in your Partner Dashboard.
What version of Shopify's Admin API's would you like to use.
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.
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)`.
Billing configurations for the app.
Override values for Shopify shop domains.
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.
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.
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.
Does your app render embedded inside the Shopify Admin or on its own. Unless you have very specific needs, this should be true.
Whether the app is initialised for local testing.
Customization options for Shopify logs.
An app-wide API access token for the storefront API. Only applies to custom apps.
REST resources to access the Admin API. You can import these from `@shopify/shopify-api/rest/admin/*`.
The scopes your app needs to access the API. Not required if using Shopify managed installation.
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.
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.
The user agent prefix to use for API requests.
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.
Billing configuration options, indexed by an app-specific plan name.
FeatureEnabled<Future, 'lineItemBilling'> extends true ? BillingConfigOneTimePlan | BillingConfigSubscriptionLineItemPlan : BillingConfigLegacyItem
Future extends FutureFlags ? Future[Flag] extends true ? true : false : false
Future flags are used to enable features that are not yet available by default.
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.
Enable line item billing, to make billing configuration more similar to the GraphQL API.
Enable support for managed pricing, so apps can check for payments without needing a billing config.
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.
Amount to charge for this plan.
Currency code for this plan.
Interval for this plan. Must be set to `OneTime`.
The line items for this plan.
The replacement behavior to use for this plan.
How many trial days to give before charging for this plan.
The amount to charge for this line item.
The currency code for this line item.
An optional discount to apply for this line item.
The recurring interval for this line item. Must be either `Every30Days` or `Annual`.
The number of intervals to apply the discount for.
The discount to apply.
The amount to discount. Cannot be set if `percentage` is set.
The percentage to discount. Cannot be set if `amount` is set.
The amount to discount. Cannot be set if `percentage` is set.
The percentage to discount. Cannot be set if `amount` is set.
The capped amount or the maximum amount to be charged in the interval.
The currency code for this line item.
The usage interval for this line item. Must be set to `Usage`.
Usage terms for this line item.
BillingConfigOneTimePlan | BillingConfigSubscriptionPlan | BillingConfigUsagePlan
Amount to charge for this plan.
Currency code for this plan.
The discount to apply to this plan.
Recurring interval for this plan. Must be either `Every30Days` or `Annual`.
The behavior to use when replacing an existing subscription with a new one.
How many trial days to give before charging for this plan.
Exclude<BillingInterval, BillingInterval.OneTime>
Amount to charge for this plan.
Currency code for this plan.
Interval for this plan. Must be set to `Usage`.
The behavior to use when replacing an existing subscription with a new one.
How many trial days to give before charging for this plan.
Usage terms for this plan.
A function to call after a merchant installs your app
Record<string, WebhookHandler | WebhookHandler[]>
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.
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)
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).
Returns a set of functions that can be used by the app's backend to be able to respond to all Shopify requests. The shape of the returned object changes depending on the value of `distribution`. If it is `AppDistribution.ShopifyAdmin`, then only `ShopifyAppBase` objects are returned, otherwise `ShopifyAppLogin` objects are included.
import { shopifyApp } from "@shopify/shopify-app-remix/server";
const shopify = shopifyApp({
// ...etc
});
export default shopify;
export const addDocumentResponseheaders = shopify.addDocumentResponseheaders;
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,
});
}
import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server";
const shopify = shopifyApp({
// ...etc
});
export default shopify;
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());
}
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
});
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
import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server";
const shopify = shopifyApp({
// ...etc
});
export default shopify;
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());
}
import { LATEST_API_VERSION, shopifyApp } from "@shopify/shopify-app-remix/server";
const shopify = shopifyApp({
// ...etc
});
export default shopify;
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>
);
}