I’m trying to create a custom discount function. The actual discount functionality is done, but I want it to add a free gift to the cart. I should be able to use the Storefront API to send a post request to add an item to the cart. However, I cannot use fetch like I normally would (https://shopify.dev/docs/apps/functions/language-support/javascript#not-available-in-javy-or-shopify-functions). After a ton of searching, it seems like one of these is the way to go to set up a client to make requests?
// possible solution
const shopify = shopifyApi({
apiKey: storefrontAccessToken,
hostName: shop,
apiSecretKey: '',
hostScheme: 'https',
apiVersion: types_1.LATEST_API_VERSION,
isEmbeddedApp: true,
isCustomStoreApp: false,
});
if (shopify) {
console.log('The client was created.');
}
// other possible solution
const storefrontClient = new shopify.clients.Storefront({domain: shop,storefrontAccessToken,});
if (storefrontClient) {
console.log('The client was created.');
} else {
console.log('The client was not created.');
}
} catch (error) {
console.error('error: ', error.message);
}
However, any time I use
import { shopifyApi } from “@shopify/shopify-api”;
I get “Error: Could not resolve crypto” (the link above also says you can’t use crypto in Shopify Functions). I haven’t done anything with crypto, so it’s being done in Shopify’s default modules that come automatically installed when you create an app.
Anyone know how to fix this? Am I setting up the API client incorrectly?
Also tried adding import ‘@shopify/shopify-api/adapters/node’; and I still get the same error about crypto.
If I do import { shopify } from “@shopify/shopify-api”; instead of import { shopifyApi } from “@shopify/shopify-api”;
then I get an error that shopify does not have a clients property, or shopify could not be found.