Installations
npm install @shopify/storefront-api-client
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM, UMD
Node Version
18.20.5
NPM Version
10.8.2
Score
98.4
Supply Chain
100
Quality
92.2
Maintenance
100
Vulnerability
100
License
Releases
@shopify/shopify-app-remix@3.7.1
Published on 31 Jan 2025
@shopify/shopify-app-express@5.0.12
Published on 31 Jan 2025
@shopify/shopify-api@11.8.1
Published on 31 Jan 2025
@shopify/shopify-app-session-storage-prisma@6.0.1
Published on 31 Jan 2025
@shopify/shopify-app-session-storage-redis@4.2.5
Published on 31 Jan 2025
@shopify/shopify-app-session-storage-sqlite@4.0.12
Published on 31 Jan 2025
Contributors
Languages
TypeScript (99.93%)
JavaScript (0.06%)
Shell (0.01%)
Developer
Shopify
Download Statistics
Total Downloads
3,097,000
Last Day
13,798
Last Week
63,020
Last Month
270,848
Last Year
3,058,306
GitHub Statistics
329 Stars
5,199 Commits
126 Forks
170 Watching
80 Branches
7,103 Contributors
Bundle Size
8.90 kB
Minified
3.60 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.4
Package Id
@shopify/storefront-api-client@1.0.4
Unpacked Size
217.53 kB
Size
54.44 kB
File Count
49
NPM Version
10.8.2
Node Version
18.20.5
Publised On
23 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
3,097,000
Last day
2.6%
13,798
Compared to previous day
Last week
-13.7%
63,020
Compared to previous week
Last month
9%
270,848
Compared to previous month
Last year
7,803.8%
3,058,306
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
1
Storefront API Client
The Storefront API Client manages the API's authentication information and provides various methods that enables devs to interacts with the API.
Getting started
Using your preferred package manager, install this package in a project:
1yarn add @shopify/storefront-api-client
1npm install @shopify/storefront-api-client --s
1pnpm add @shopify/storefront-api-client
CDN
The UMD builds of each release version are available via the unpkg
CDN
1// The minified `0.2.3` version of the Storefront API Client 2<script src="https://unpkg.com/@shopify/storefront-api-client@0.2.3/dist/umd/storefront-api-client.min.js"></script> 3 4<script> 5 const client = ShopifyStorefrontAPIClient.createStorefrontApiClient({...}); 6</script>
Initialization
Public access token client initialization
1import {createStorefrontApiClient} from '@shopify/storefront-api-client'; 2 3const client = createStorefrontApiClient({ 4 storeDomain: 'http://your-shop-name.myshopify.com', 5 apiVersion: '2023-10', 6 publicAccessToken: 'your-storefront-public-access-token', 7});
Create a server enabled client using a private access token and a custom Fetch API
[!WARNING] Private Storefront API delegate access tokens should only be used in server-to-server implementations and not within a browser environment.
In order to use the client within a server, a server enabled JS Fetch API will need to be provided to the client at initialization.
1import { 2 createStorefrontApiClient, 3 CustomFetchApi, 4} from '@shopify/storefront-api-client'; 5import {fetch as nodeFetch} from 'node-fetch'; 6 7const client = createStorefrontApiClient({ 8 storeDomain: 'http://your-shop-name.myshopify.com', 9 apiVersion: '2023-10', 10 privateAccessToken: 'your-storefront-private-access-token', 11 customFetchApi: nodeFetch, 12});
createStorefrontApiClient()
parameters
Property | Type | Description |
---|---|---|
storeDomain | string | The domain of the store. It can be the Shopify myshopify.com domain or a custom store domain. |
apiVersion | string | The requested Storefront API version |
publicAccessToken? | string | Storefront API public access token. Either publicAccessToken or privateAccessToken must be provided at initialization. |
privateAccessToken? | string | Storefront API private access token. Either publicAccessToken or privateAccessToken must be provided at initialization. Important: Storefront API private delegate access tokens should only be used in a server-to-server implementation. |
clientName? | string | Name of the client |
retries? | number | The number of HTTP request retries if the request was abandoned or the server responded with a Too Many Requests (429) or Service Unavailable (503) response. Default value is 0 . Maximum value is 3 . |
customFetchAPI? | (url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response> | A replacement fetch function that will be used in all client network requests. By default, the client uses window.fetch() . |
logger? | (logContent: UnsupportedApiVersionLog | HTTPResponseLog | HTTPRetryLog ) => void | A logger function that accepts log content objects. This logger will be called in certain conditions with contextual information. |
Client properties
Property | Type | Description |
---|---|---|
config | StorefrontApiClientConfig | Configuration for the client |
getHeaders | (headers?: Record<string, string | string[]>) => Record<string, string | string[]> | Returns Storefront API specific headers needed to interact with the API. If additional headers are provided, the custom headers will be included in the returned headers object. |
getApiUrl | (apiVersion?: string) => string | Returns the shop specific API url. If an API version is provided, the returned URL will include the provided version, else the URL will include the API version set at client initialization. |
fetch | (operation: string, options?: ApiClientRequestOptions ) => Promise<Response> | Fetches data from Storefront API using the provided GQL operation string and ApiClientRequestOptions object and returns the network response. |
request | <TData>(operation: string, options?: ApiClientRequestOptions ) => Promise< ClientResponse<TData> > | Requests data from Storefront API using the provided GQL operation string and ApiClientRequestOptions object and returns a normalized response object. |
requestStream | <TData>(operation: string, options?: RequestOptions ) => Promise <AsyncIterator< ClientStreamResponse<TData> >> | Fetches GQL operations (eg. @defer directive) that can result in a streamed response from the Storefront API . The function returns an async iterator and the iterator will return normalized stream response objects as data becomes available through the stream. |
StorefrontApiClientConfig
properties
Name | Type | Description |
---|---|---|
storeDomain | string | The secure store domain |
apiVersion | string | The Storefront API version to use in the API request |
publicAccessToken | string | never | The provided public access token. If privateAccessToken was provided, publicAccessToken will not be available. |
privateAccessToken | string | never | The provided private access token. If publicAccessToken was provided, privateAccessToken will not be available. |
headers | Record<string, string | string[]> | The headers generated by the client during initialization |
apiUrl | string | The API URL generated from the provided store domain and api version |
clientName? | string | The provided client name |
retries? | number | The number of retries the client will attempt when the API responds with a Too Many Requests (429) or Service Unavailable (503) response |
ApiClientRequestOptions
properties
Name | Type | Description |
---|---|---|
variables? | Record<string, any> | Variable values needed in the graphQL operation |
apiVersion? | string | The Storefront API version to use in the API request |
headers? | Record<string, string | string[]> | Customized headers to be included in the API request |
retries? | number | Alternative number of retries for the request. Retries only occur for requests that were abandoned or if the server responds with a Too Many Request (429) or Service Unavailable (503) response. Minimum value is 0 and maximum value is 3 . |
ClientResponse<TData>
Name | Type | Description |
---|---|---|
data? | TData | any | Data returned from the Storefront API. If TData was provided to the function, the return type is TData , else it returns type any . |
errors? | ResponseErrors | Errors object that contains any API or network errors that occured while fetching the data from the API. It does not include any UserErrors . |
extensions? | Record<string, any> | Additional information on the GraphQL response data and context. It can include the context object that contains the context settings used to generate the returned API response. |
ClientStreamResponse<TData>
Name | Type | Description |
---|---|---|
data? | TData | any | Currently available data returned from the Storefront API. If TData was provided to the function, the return type is TData , else it returns type any . |
errors? | ResponseErrors | Errors object that contains any API or network errors that occured while fetching the data from the API. It does not include any UserErrors . |
extensions? | Record<string, any> | Additional information on the GraphQL response data and context. It can include the context object that contains the context settings used to generate the returned API response. |
hasNext | boolean | Flag to indicate whether the response stream has more incoming data |
ResponseErrors
Name | Type | Description |
---|---|---|
networkStatusCode? | number | HTTP response status code |
message? | string | The provided error message |
graphQLErrors? | any[] | The GraphQL API errors returned by the server |
response? | Response | The raw response object from the network fetch call |
Client request()
response examples
Successful response
API response
1{ 2 "data": { 3 "product": { 4 "id": "gid://shopify/Product/12345678912", 5 "title": "Sample product # 1" 6 } 7 }, 8 "extensions": { 9 "context": { 10 "country": "US", 11 "language": "EN" 12 } 13 } 14}
Error responses
Network error
1{ 2 "errors": { 3 "networkStatusCode": 401, 4 "message": "" 5 } 6}
Storefront API graphQL error
1{ 2 "errors": { 3 "networkStatusCode": 200, 4 "message": "An error occurred while fetching from the API. Review the `graphQLErrors` object for details.", 5 "graphQLErrors": [ 6 { 7 "message": "Field 'testField' doesn't exist on type 'Product'", 8 "locations": [ 9 { 10 "line": 17, 11 "column": 3 12 } 13 ], 14 "path": ["fragment ProductFragment", "testField"], 15 "extensions": { 16 "code": "undefinedField", 17 "typeName": "Product", 18 "fieldName": "testField" 19 } 20 } 21 ] 22 } 23}
Usage examples
Query for a product
1const productQuery = ` 2 query ProductQuery($handle: String) { 3 product(handle: $handle) { 4 id 5 title 6 handle 7 } 8 } 9`; 10 11const {data, errors, extensions} = await client.request(productQuery, { 12 variables: { 13 handle: 'sample-product', 14 }, 15});
Query for product info using the @defer
directive
1const productQuery = ` 2 query ProductQuery($handle: String) { 3 product(handle: $handle) { 4 id 5 handle 6 ... @defer(label: "deferredFields") { 7 title 8 description 9 } 10 } 11 } 12`; 13 14const responseStream = await client.requestStream(productQuery, { 15 variables: {handle: 'sample-product'}, 16}); 17 18// await available data from the async iterator 19for await (const response of responseStream) { 20 const {data, errors, extensions, hasNext} = response; 21}
Create a localized cart
1const cartCreateMutation = ` 2 mutation ($input: CartInput!, $country: CountryCode, $language: LanguageCode) 3 @inContext(country: $country, language: $language) { 4 cartCreate(input: $input) { 5 userErrors { 6 message 7 code 8 field 9 } 10 cart { 11 id 12 checkoutUrl 13 } 14 } 15 } 16`; 17 18const {data, errors, extensions} = await client.request(cartCreateMutation, { 19 variables: { 20 input: {}, 21 country: 'JP', 22 language: 'JA', 23 }, 24});
Query for shop information
1const shopQuery = ` 2 query shop { 3 shop { 4 name 5 id 6 } 7 } 8`; 9 10const {data, errors, extensions} = await client.request(shopQuery);
Dynamically set the Storefront API version per request
1const productQuery = ` 2 query ProductQuery($handle: String) { 3 product(handle: $handle) { 4 id 5 title 6 handle 7 } 8 } 9`; 10 11const {data, errors, extensions} = await client.request(productQuery, { 12 variables: { 13 handle: 'sample-product', 14 }, 15 apiVersion: '2023-07', 16});
Add custom headers to API request
1const productQuery = ` 2 query ProductQuery($handle: String) { 3 product(handle: $handle) { 4 id 5 title 6 handle 7 } 8 } 9`; 10 11const {data, errors, extensions} = await client.request(productQuery, { 12 variables: { 13 handle: 'sample-product', 14 }, 15 headers: { 16 'Shopify-Storefront-Id': 'shop-id', 17 }, 18});
Dynamically set the number of retries per request
1const productQuery = ` 2 query ProductQuery($handle: String) { 3 product(handle: $handle) { 4 id 5 title 6 handle 7 } 8 } 9`; 10 11const {data, errors, extensions} = await client.request(productQuery, { 12 variables: { 13 handle: 'sample-product', 14 }, 15 retries: 2, 16});
Provide GQL query type to client.request()
and client.requestStream()
1import {print} from 'graphql/language'; 2 3// GQL operation types are usually auto generated during the application build 4import {CollectionQuery, CollectionDeferredQuery} from 'types/appTypes'; 5import collectionQuery from './collectionQuery.graphql'; 6import collectionDeferredQuery from './collectionDeferredQuery.graphql'; 7 8const {data, errors, extensions} = await client.request<CollectionQuery>( 9 print(collectionQuery), 10 { 11 variables: { 12 handle: 'sample-collection', 13 }, 14 }, 15); 16 17const responseStream = await client.requestStream<CollectionDeferredQuery>( 18 print(collectionDeferredQuery), 19 { 20 variables: {handle: 'sample-collection'}, 21 }, 22);
Using client.fetch()
to get API data
1const shopQuery = ` 2 query shop { 3 shop { 4 name 5 id 6 } 7 } 8`; 9 10const response = await client.fetch(shopQuery); 11 12if (response.ok) { 13 const {errors, data, extensions} = await response.json(); 14}
Typing variables and return objects
This client is compatible with the @shopify/api-codegen-preset
package.
You can use that package to create types from your operations with the Codegen CLI.
There are different ways to configure codegen with it, but the simplest way is to:
-
Add the preset package as a dev dependency to your project, for example:
1npm install --save-dev @shopify/api-codegen-preset
-
Create a
.graphqlrc.ts
file in your root containing:1import {ApiType, shopifyApiProject} from '@shopify/api-codegen-preset'; 2 3export default { 4 schema: 'https://shopify.dev/storefront-graphql-direct-proxy', 5 documents: ['*.ts', '!node_modules'], 6 projects: { 7 default: shopifyApiProject({ 8 apiType: ApiType.Storefront, 9 apiVersion: '2023-10', 10 outputDir: './types', 11 }), 12 }, 13};
-
Add
"graphql-codegen": "graphql-codegen"
to yourscripts
section inpackage.json
. -
Tag your operations with
#graphql
, for example:1const {data, errors, extensions} = await client.request( 2 `#graphql 3 query Shop { 4 shop { 5 name 6 } 7 }`, 8); 9console.log(data?.shop.name);
-
Run
npm run graphql-codegen
to parse the types from your operations.
[!NOTE] Remember to ensure that your tsconfig includes the files under
./types
!
Once the script runs, it'll create the file ./types/storefront.generated.d.ts
.
When TS includes that file, it'll automatically cause the client to detect the types for each query.
Log Content Types
UnsupportedApiVersionLog
This log content is sent to the logger whenever an unsupported API version is provided to the client.
Property | Type | Description |
---|---|---|
type | LogType['Unsupported_Api_Version'] | The type of log content. Is always set to Unsupported_Api_Version |
content | {apiVersion: string, supportedApiVersions: string[]} | Contextual info including the provided API version and the list of currently supported API versions. |
HTTPResponseLog
This log content is sent to the logger whenever a HTTP response is received by the client.
Property | Type | Description |
---|---|---|
type | LogType['HTTP-Response'] | The type of log content. Is always set to HTTP-Response |
content | { requestParams : [url, init?], response: Response} | Contextual data regarding the request and received response |
HTTPRetryLog
This log content is sent to the logger whenever the client attempts to retry HTTP requests.
Property | Type | Description |
---|---|---|
type | LogType['HTTP-Retry'] | The type of log content. Is always set to HTTP-Retry |
content | { requestParams : [url, init?], lastResponse?: Response, retryAttempt: number, maxRetries: number} | Contextual data regarding the upcoming retry attempt. requestParams : parameters used in the requestlastResponse : previous response retryAttempt : the current retry attempt count maxRetries : the maximum number of retries |
RequestParams
Property | Type | Description |
---|---|---|
url | string | Requested URL |
init? | {method?: string, headers?: HeaderInit, body?: string} | The request information |
Gotchas / Troubleshooting
URL validation errors when using React Native
If you're using this package in a React Native project, you might encounter URL validation errors when initializing the storefront api client. For example:
Error: Storefront API Client: a valid store domain ("http://shop.myshopify.com/") must be provided
To avoid issues:
- Install the
react-native-url-polyfill
package:
1npm i react-native-url-polyfill
- Add the following import to the top of your entry file, typically
index.js
:
1import 'react-native-url-polyfill/auto';
This will apply a global polyfill for the URL
object, allowing you to instantiate the storefront api client without encountering URL validation errors.
No vulnerabilities found.
No security vulnerabilities found.
Other packages similar to @shopify/storefront-api-client
@shopify/graphql-client
Shopify GraphQL Client - A lightweight generic GraphQL JS client to interact with Shopify GraphQL APIs
typed-shopify-storefront
Typed client for the Shopify Storefront GraphQL API
shopify-storefront-client
A customizable module to interact with Shopify's Storefront API.
@balancedbody/shopify-storefront-client
A customizable module to interact with Shopify's Storefront API, modified for use by Balanced Body