Providers
Provider preset builders and provider-specific SDK exports for configuring Haus Storefront data providers consistently.
Purpose
This library packages reusable provider setup so apps can configure DataProvider with a single preset instead of manually wiring SDK instances, interceptors, persisted settings, and provider-specific defaults every time.
Use it when you want:
- A fluent preset builder for composing
DataProviderconfiguration - Vendure-specific defaults such as auth/channel interceptors and locale or currency bootstrapping
- Direct access to the Vendure SDK, generated query definitions, and reusable fragments
Features
- Preset builder API:
ProviderPresetcomposes API URL, persistence, interceptors, custom providers, SDKs, and mount hooks - Vendure-ready preset:
VendureProviderPresetadds a configuredVendureSDKplus request/response interceptors - Typed SDK methods:
VendureSDKexposes storefront operations for products, search, cart, customer, account, and checkout flows - Reusable query exports:
vendureQueriesexposes the underlying builder queries for custom query composition - Shared fragments: Detailed product, listed product, order detail, and customer order list fragments are exported for reuse
Installation
- npm
- Yarn
npm install @haus-storefront-react/providers
yarn add @haus-storefront-react/providers
Note: This is not a public package. Contact the Haus Tech Team for access.
API Reference
Classes
ProviderPreset
Fluent base builder for provider presets. It wraps the DataProvider preset shape from @haus-storefront-react/core and lets provider-specific presets extend it.
Constructor
type ProviderPresetOptions = {
apiUrl?: string
persistOptions?: PersistOptions
persistBusterResolver?: (() => Promise<string>) | string
customProviders?: ComponentType<{ children: ReactNode }>
}
class ProviderPreset<TSdk = NonNullable<CoreProviderPreset['sdk']>> {
constructor(
preset: Omit<CoreProviderPreset, 'sdk'> & { sdk?: TSdk },
baseOptions?: BaseOptions,
)
}
Methods
| Method | Signature | Description |
|---|---|---|
withApiUrl | (apiUrl: string) => this | Sets preset.options.apiUrl |
withPersistOptions | (persistOptions?: PersistOptions) => this | Configures React Query persistence |
withPersistBuster | (resolver?: (() => Promise<string>) | string) => this | Adds a persistence buster resolver/string |
withCustomProviders | (customProviders?: ComponentType<{ children: ReactNode }>) => this | Wraps app content in additional providers |
withInterceptors | ({ request?, response? }) => this | Sets request/response interceptor strategies |
withSdk | (sdk: TSdk) => this | Injects an SDK instance into the preset |
withOnMount | (onMount: CoreProviderPreset['onMount']) => this | Composes an extra mount lifecycle hook |
toPreset | () => Omit<CoreProviderPreset, 'sdk'> & { sdk?: TSdk } | Returns a DataProvider-ready preset object |
VendureProviderPreset
Provider-specific preset builder for Vendure. It applies the built-in Vendure interceptors, optionally creates a VendureSDK, and seeds locale/currency/channel defaults into storage on mount.
Options
interface VendureProviderPresetOptions extends BaseOptions {
withSdk?: boolean
defaultChannelToken?: string
locale?: string
currency?: string
}
Behavior
withSdkdefaults totrue, so a newVendureSDKis created unless you explicitly disable itdefaultChannelTokenis stored asdefaultChannelTokenon mountlocaleandcurrencyare stored aslangandcurrencyCodewhen those values are not already present- Vendure request/response interceptors are applied automatically
VendureSDK
Vendure storefront SDK built on top of GraphQLSDK from @haus-storefront-react/core.
It provides typed helper methods for common storefront operations while still inheriting the lower-level GraphQL utilities from GraphQLSDK.
Representative methods
| Method | Signature | Description |
|---|---|---|
activeChannel | () => Promise<Channel> | Fetches the active Vendure channel |
activeCustomer | () => Promise<Customer> | Fetches the signed-in customer |
activeOrder | () => Promise<Order> | Fetches the current active order |
product | (id?: string, slug?: string) => Promise<Product> | Fetches a product by ID or slug |
collections | (options?: unknown) => Promise<CollectionList> | Fetches collections |
search | (input: SearchInput) => Promise<SearchResponse> | Runs product search |
searchField | (input: SearchInput) => Promise<UseSearchFieldResponse | null> | Runs enriched autocomplete/search-field queries |
addItemToOrder | (input: AddItemToOrderInput) => Promise<Order> | Adds a single item to the active order |
addItemsToOrder | (inputs: AddItemToOrderInput[]) => Promise<UpdateMultipleOrderItemsResult> | Adds multiple order lines in one call |
adjustOrderLine | (input: AdjustOrderLineInput) => Promise<Order> | Updates order line quantity |
removeOrderLine | (lineId: string) => Promise<Order> | Removes an order line |
updateOrder | ({ input }: { input: UpdateOrderInput; id?: string }) => Promise<Order> | Updates addresses, shipping, payment, customer, custom fields, or coupon state |
eligibleShippingMethods | () => Promise<ShippingMethodQuote[]> | Loads shipping methods for checkout |
eligiblePaymentMethods | () => Promise<PaymentMethodQuote[]> | Loads payment methods for checkout |
login / logout | (input: LoginInput) => Promise<unknown> / () => Promise<unknown> | Account authentication helpers |
setChannelToken | (token: string, asDefaultToken?: boolean) => Promise<void> | Persists channel token selection |
Notes:
VendureSDKalso inherits generic GraphQL helpers such ascreateGraphQLQuery,createGraphQLMutation, and request execution helpers fromGraphQLSDKsearchField()enriches the raw response with collection matching, grouping, and breadcrumb generation hooks
Utilities
vendureRequestInterceptor
Request interceptor that applies persisted Vendure auth and storefront context before each request.
Behavior
- Adds
Authorization: Bearer <token>from storedauth_token - Adds
vendure-tokenfrom storedchannelTokenordefaultChannelToken - Adds
currencyCodeandlanguageCodequery params from stored preferences - Creates the visitor's session before the first request that has none. Without a token, Vendure would create a separate anonymous session for every concurrent request that needs one, and the first item added to the cart could land in a session that is then forgotten. So one small
activeOrderrequest (afetchPOST to the same Shop API URL, with the samevendure-tokenandcredentials: 'include'like the library's axios instances) creates the session, its token is stored asauth_token, and every other request without a token waits for it and then sends that token.- The wait is per storage adapter (
getStorageAdapter()fromcore), so two visitors never wait on each other. - It runs in the browser and React Native only. On a server with request-scoped storage, requests without a token go out at once, as before: the browser owns the session, and a session created while rendering would be discarded.
- If the bootstrap fails or takes longer than 10 seconds, the waiting requests go out without a token and the next one tries again. The failure is logged through the library logger (
logger.warn, shown when thedebugflag is on). If Vendure answers without avendure-auth-tokenheader (for example cookie-only sessions), later requests skip the bootstrap.
- The wait is per storage adapter (
vendureResponseInterceptor
Response interceptor that persists the vendure-auth-token response header to storage as auth_token.
vendureQueries
Namespace export containing the Vendure builder queries used by VendureSDK. Use this when you need to extend or reuse the default query definitions.
Exported fragments
Reusable GraphQL field arrays exported from @haus-storefront-react/providers/vendure:
| Export | Description |
|---|---|
detailedProductFragment | Rich product detail fields including assets, collections, facet values, variants, and option groups |
listedProductFragment | Product listing/search result fields including price ranges, assets, and collection/facet IDs |
orderDetailFragment | Rich order detail fields for checkout, account, and order history views |
activeCustomerOrderList | Compact customer order list fields for account overview screens |
Basic Usage
Configure DataProvider with a Vendure preset
- React
- React Native
import { DataProvider } from '@haus-storefront-react/core'
import { VendureProviderPreset } from '@haus-storefront-react/providers/vendure'
const preset = new VendureProviderPreset({
apiUrl: 'https://your-vendure-instance.com/shop-api',
defaultChannelToken: 'default-channel',
locale: 'en',
currency: 'USD',
persistOptions: {
enabled: true,
},
}).toPreset()
function App() {
return (
<DataProvider platform='web' preset={preset}>
{/* Your app components */}
</DataProvider>
)
}
import { DataProvider } from '@haus-storefront-react/core'
import { VendureProviderPreset } from '@haus-storefront-react/providers/vendure'
const preset = new VendureProviderPreset({
apiUrl: 'https://your-vendure-instance.com/shop-api',
defaultChannelToken: 'default-channel',
locale: 'en',
currency: 'USD',
persistOptions: {
enabled: true,
},
}).toPreset()
function App() {
return (
<DataProvider platform='native' preset={preset}>
{/* Your app components */}
</DataProvider>
)
}
Use the Vendure SDK directly
- React
- React Native
import { useEffect } from 'react'
import { useSdk } from '@haus-storefront-react/core'
import type { VendureSDK } from '@haus-storefront-react/providers/vendure'
function ProductSearch() {
const sdk = useSdk() as VendureSDK
useEffect(() => {
sdk.search({ term: 'hoodie', groupByProduct: true }).then((result) => {
console.log(result.items)
})
}, [sdk])
return null
}
import { useEffect } from 'react'
import { Text } from 'react-native'
import { useSdk } from '@haus-storefront-react/core'
import type { VendureSDK } from '@haus-storefront-react/providers/vendure'
function ProductSearch() {
const sdk = useSdk() as VendureSDK
useEffect(() => {
sdk.search({ term: 'hoodie', groupByProduct: true }).then((result) => {
console.log(result.items)
})
}, [sdk])
return <Text>Searching...</Text>
}
Advanced Usage
Compose a preset fluently
- React
- React Native
import { DataProvider } from '@haus-storefront-react/core'
import { VendureProviderPreset } from '@haus-storefront-react/providers/vendure'
const preset = new VendureProviderPreset({
apiUrl: 'https://your-vendure-instance.com/shop-api',
defaultChannelToken: 'b2c',
})
.withPersistOptions({ enabled: true, maxAge: 1000 * 60 * 60 })
.withOnMount(async ({ sdk }) => {
await sdk?.activeChannel()
})
.toPreset()
function App() {
return <DataProvider platform='web' preset={preset}>{/* App */}</DataProvider>
}
import { DataProvider } from '@haus-storefront-react/core'
import { VendureProviderPreset } from '@haus-storefront-react/providers/vendure'
const preset = new VendureProviderPreset({
apiUrl: 'https://your-vendure-instance.com/shop-api',
defaultChannelToken: 'b2c',
})
.withPersistOptions({ enabled: true, maxAge: 1000 * 60 * 60 })
.withOnMount(async ({ sdk }) => {
await sdk?.activeChannel()
})
.toPreset()
function App() {
return <DataProvider platform='native' preset={preset}>{/* App */}</DataProvider>
}
Supply your own Vendure SDK instance
This is useful when you want to subclass VendureSDK, override request behavior, or inject additional custom methods before passing the preset into DataProvider.
import { DataProvider } from '@haus-storefront-react/core'
import { VendureProviderPreset, VendureSDK } from '@haus-storefront-react/providers/vendure'
class CustomVendureSDK extends VendureSDK {
async featuredProducts() {
return this.search({ term: 'featured', groupByProduct: true })
}
}
const preset = new VendureProviderPreset({
withSdk: false,
apiUrl: 'https://your-vendure-instance.com/shop-api',
})
.withSdk(new CustomVendureSDK())
.toPreset()
function App() {
return <DataProvider platform='web' preset={preset}>{/* App */}</DataProvider>
}
Reuse exported Vendure fragments
The fragment exports can be used when extending Vendure query definitions or building custom query maps on top of the default provider queries.
import { detailedProductFragment, vendureQueries } from '@haus-storefront-react/providers/vendure'
const productQuery = {
...vendureQueries.product,
fields: [
'id',
'name',
...detailedProductFragment,
],
}
Migration Notes
1.0.20: session bootstrap (behaviour change)
- A browser or React Native request without a session token now first sends one
fetchPOST (query SessionBootstrap { activeOrder { id } }) to the Shop API, and waits for it, before the request itself goes out (#118). Server rendering with request-scoped storage is unchanged. - A server without
configureRequestStorage(wherestorageis a no-op) skips the bootstrap too, becausegetStorageAdapter()isnullthere. - The bootstrap is built from the request that triggered it: it carries that request's axios headers (for example a gateway key or
Accept-Languagefrom your axios defaults), including your ownAuthorizationheader or axiosauthoption (sent as basic auth), and itsparamsas a query string, next tocontent-typeandvendure-token. The bootstrap only runs while there is no session token, so anAuthorizationheader there is always yours, never the library's bearer token. If the Shop API still answers it with an error status, requests for that visitor go out without a token for 5 seconds before another bootstrap is tried. The failure is logged with the library's debug flag, like an unreachable endpoint. - Test suites that mock axios but not
fetchsee one extra call per tokenless visitor. Without a stub, the realfetch(built into Node 18 and later) runs against the configured API URL; when it fails or times out after 10 seconds, the requests go out without a token. Stubfetch(for examplevi.stubGlobal('fetch', ...)returning a response with avendure-auth-tokenheader), or seedauth_tokenin storage so the bootstrap is skipped.
Made with ❤️ by Haus Tech Team