Skip to main content

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 DataProvider configuration
  • 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: ProviderPreset composes API URL, persistence, interceptors, custom providers, SDKs, and mount hooks
  • Vendure-ready preset: VendureProviderPreset adds a configured VendureSDK plus request/response interceptors
  • Typed SDK methods: VendureSDK exposes storefront operations for products, search, cart, customer, account, and checkout flows
  • Reusable query exports: vendureQueries exposes 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 install @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

MethodSignatureDescription
withApiUrl(apiUrl: string) => thisSets preset.options.apiUrl
withPersistOptions(persistOptions?: PersistOptions) => thisConfigures React Query persistence
withPersistBuster(resolver?: (() => Promise<string>) | string) => thisAdds a persistence buster resolver/string
withCustomProviders(customProviders?: ComponentType<{ children: ReactNode }>) => thisWraps app content in additional providers
withInterceptors({ request?, response? }) => thisSets request/response interceptor strategies
withSdk(sdk: TSdk) => thisInjects an SDK instance into the preset
withOnMount(onMount: CoreProviderPreset['onMount']) => thisComposes 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

  • withSdk defaults to true, so a new VendureSDK is created unless you explicitly disable it
  • defaultChannelToken is stored as defaultChannelToken on mount
  • locale and currency are stored as lang and currencyCode when 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

MethodSignatureDescription
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:

  • VendureSDK also inherits generic GraphQL helpers such as createGraphQLQuery, createGraphQLMutation, and request execution helpers from GraphQLSDK
  • searchField() 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 stored auth_token
  • Adds vendure-token from stored channelToken or defaultChannelToken
  • Adds currencyCode and languageCode query 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 activeOrder request (a fetch POST to the same Shop API URL, with the same vendure-token and credentials: 'include' like the library's axios instances) creates the session, its token is stored as auth_token, and every other request without a token waits for it and then sends that token.
    • The wait is per storage adapter (getStorageAdapter() from core), 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 the debug flag is on). If Vendure answers without a vendure-auth-token header (for example cookie-only sessions), later requests skip the bootstrap.

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:

ExportDescription
detailedProductFragmentRich product detail fields including assets, collections, facet values, variants, and option groups
listedProductFragmentProduct listing/search result fields including price ranges, assets, and collection/facet IDs
orderDetailFragmentRich order detail fields for checkout, account, and order history views
activeCustomerOrderListCompact customer order list fields for account overview screens

Basic Usage​

Configure DataProvider with a Vendure preset​

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>
)
}

Use the Vendure SDK directly​

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
}

Advanced Usage​

Compose a preset fluently​

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>
}

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 fetch POST (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 (where storage is a no-op) skips the bootstrap too, because getStorageAdapter() is null there.
  • The bootstrap is built from the request that triggered it: it carries that request's axios headers (for example a gateway key or Accept-Language from your axios defaults), including your own Authorization header or axios auth option (sent as basic auth), and its params as a query string, next to content-type and vendure-token. The bootstrap only runs while there is no session token, so an Authorization header 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 fetch see one extra call per tokenless visitor. Without a stub, the real fetch (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. Stub fetch (for example vi.stubGlobal('fetch', ...) returning a response with a vendure-auth-token header), or seed auth_token in storage so the bootstrap is skipped.

Made with ❤️ by Haus Tech Team