create Hydrogen Context
The function creates the context object required to use Hydrogen utilities throughout a Hydrogen project.
Anchor to createhydrogencontext(options)createHydrogenContext(options)
- Anchor to envenvenvTEnvTEnvrequiredrequired
- Anchor to requestrequestrequestCrossRuntimeRequestCrossRuntimeRequestrequiredrequired
- Anchor to sessionsessionsessionTSessionTSessionrequiredrequired
Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use another session storage implementation.
- Anchor to buyerIdentitybuyerIdentitybuyerIdentityCartBuyerIdentityInputCartBuyerIdentityInput
Buyer identity. Default buyer identity is passed to cartCreate.
- Anchor to cachecachecacheCacheCache
An instance that implements the Cache API
- Anchor to cartcartcart{ getId?: () => string; setId?: (cartId: string) => Headers; queryFragment?: string; mutateFragment?: string; customMethods?: Record<string, Function>; }{ getId?: () => string; setId?: (cartId: string) => Headers; queryFragment?: string; mutateFragment?: string; customMethods?: Record<string, Function>; }
Cart handler overwrite options. See documentation for createCartHandler for more information.
- Anchor to customerAccountcustomerAccountcustomerAccount{ apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; }{ apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; }
Customer Account client overwrite options. See documentation for createCustomerAccountClient for more information.
- Anchor to i18ni18ni18nTI18nTI18n
An object containing a country code and language code
- Anchor to logErrorslogErrorslogErrorsboolean | ((error?: Error) => boolean)boolean | ((error?: Error) => boolean)
Whether it should print GraphQL errors automatically. Defaults to true
- Anchor to storefrontstorefrontstorefront{ headers?: StorefrontHeaders; apiVersion?: string; }{ headers?: StorefrontHeaders; apiVersion?: string; }
Storefront client overwrite options. See documentation for createStorefrontClient for more information.
- Anchor to waitUntilwaitUntilwaitUntilWaitUntilWaitUntil
The
function is used to keep the current request/response lifecycle alive even after a response has been sent. It should be provided by your platform.
CartBuyerIdentityInput
Headers
CrossRuntimeRequest
- headers
{ [key: string]: any; get?: (key: string) => string; } - method
string - url
string
Anchor to returnsReturns
- Anchor to cartcartcartTCustomMethods extends CustomMethodsBase ? HydrogenCartCustom<TCustomMethods> : HydrogenCartTCustomMethods extends CustomMethodsBase ? HydrogenCartCustom<TCustomMethods> : HydrogenCartrequiredrequired
A collection of utilities used to interact with the cart.
- Anchor to customerAccountcustomerAccountcustomerAccountCustomerAccountCustomerAccountrequiredrequired
A GraphQL client for querying the Customer Account API. It also provides methods to authenticate and check if the user is logged in.
- Anchor to envenvenvTEnvTEnvrequiredrequired
- Anchor to sessionsessionsessionTSessionTSessionrequiredrequired
Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use another session storage implementation.
- Anchor to storefrontstorefrontstorefrontStorefront<TI18n>Storefront<TI18n>requiredrequired
A GraphQL client for querying the Storefront API.
- Anchor to waitUntilwaitUntilwaitUntilWaitUntilWaitUntil
The
function is used to keep the current request/response lifecycle alive even after a response has been sent. It should be provided by your platform.
CustomMethodsBase
HydrogenCartCustom
Omit<HydrogenCart, keyof TCustomMethods> & TCustomMethodsHydrogenCart
- addDeliveryAddresses
Adds delivery addresses to the cart. This function sends a mutation to the storefront API to add one or more delivery addresses to the cart. It returns the result of the mutation, including any errors that occurred.
ReturnType<typeof cartDeliveryAddressesAddDefault> - addGiftCardCodes
ReturnType<typeof cartGiftCardCodesAddDefault> - addLines
ReturnType<typeof cartLinesAddDefault> - create
ReturnType<typeof cartCreateDefault> - deleteMetafield
ReturnType<typeof cartMetafieldDeleteDefault> - get
ReturnType<typeof cartGetDefault> - getCartId
() => string - removeDeliveryAddresses
Removes delivery addresses from the cart. This function sends a mutation to the storefront API to remove one or more delivery addresses from the cart. It returns the result of the mutation, including any errors that occurred.
ReturnType< typeof cartDeliveryAddressesRemoveDefault > - removeGiftCardCodes
ReturnType<typeof cartGiftCardCodesRemoveDefault> - removeLines
ReturnType<typeof cartLinesRemoveDefault> - replaceDeliveryAddresses
Replaces all delivery addresses on the cart. This function sends a mutation to the storefront API to replace all delivery addresses on the cart with the provided addresses. It returns the result of the mutation, including any errors that occurred.
ReturnType< typeof cartDeliveryAddressesReplaceDefault > - setCartId
(cartId: string) => Headers - setMetafields
ReturnType<typeof cartMetafieldsSetDefault> - updateAttributes
ReturnType<typeof cartAttributesUpdateDefault> - updateBuyerIdentity
ReturnType<typeof cartBuyerIdentityUpdateDefault> - updateDeliveryAddresses
Updates delivery addresses in the cart. This function sends a mutation to the storefront API to update one or more delivery addresses in the cart. It returns the result of the mutation, including any errors that occurred.
ReturnType< typeof cartDeliveryAddressesUpdateDefault > - updateDiscountCodes
ReturnType<typeof cartDiscountCodesUpdateDefault> - updateGiftCardCodes
ReturnType<typeof cartGiftCardCodesUpdateDefault> - updateLines
ReturnType<typeof cartLinesUpdateDefault> - updateNote
ReturnType<typeof cartNoteUpdateDefault> - updateSelectedDeliveryOption
ReturnType< typeof cartSelectedDeliveryOptionsUpdateDefault >
Headers
CustomerAccount
- authorize
On successful login, the customer redirects back to your app. This function validates the OAuth response and exchanges the authorization code for an access token and refresh token. It also persists the tokens on your session. This function should be called and returned from the Remix loader configured as the redirect URI within the Customer Account API settings in admin.
() => Promise<Response> - getAccessToken
Returns CustomerAccessToken if the customer is logged in. It also run a expiry check and does a token refresh if needed.
() => Promise<string> - getApiUrl
Creates the fully-qualified URL to your store's GraphQL endpoint.
() => string - getBuyer
Get buyer token and company location id from session.
() => Promise<BuyerInput> - handleAuthStatus
Check for a not logged in customer and redirect customer to login page. The redirect can be overwritten with `customAuthStatusHandler` option.
() => void | DataFunctionValue - i18n
The i18n configuration for Customer Account API
{ language: LanguageCode; } - isLoggedIn
Returns if the customer is logged in. It also checks if the access token is expired and refreshes it if needed.
() => Promise<boolean> - login
Start the OAuth login flow. This function should be called and returned from a Remix loader. It redirects the customer to a Shopify login domain. It also defined the final path the customer lands on at the end of the oAuth flow with the value of the `return_to` query param. (This is automatically setup unless `customAuthStatusHandler` option is in use)
(options?: LoginOptions) => Promise<Response> - logout
Logout the customer by clearing the session and redirecting to the login domain. It should be called and returned from a Remix action. The path app should redirect to after logout can be setup in Customer Account API settings in admin.
(options?: LogoutOptions) => Promise<Response> - mutate
Execute a GraphQL mutation against the Customer Account API. This method execute `handleAuthStatus()` ahead of mutation.
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(mutation: RawGqlString, ...options: ClientVariablesInRestParams<CustomerAccountMutations, RawGqlString>) => Promise<Omit<CustomerAPIResponse<ClientReturn<CustomerAccountMutations, RawGqlString, OverrideReturnType>>, "errors"> & { errors?: Pick<GraphQLError, "name" | "message" | "path" | "extensions" | "locations" | "stack">[]; }> - query
Execute a GraphQL query against the Customer Account API. This method execute `handleAuthStatus()` ahead of query.
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(query: RawGqlString, ...options: ClientVariablesInRestParams<CustomerAccountQueries, RawGqlString>) => Promise<Omit<CustomerAPIResponse<ClientReturn<CustomerAccountQueries, RawGqlString, OverrideReturnType>>, "errors"> & { errors?: Pick<GraphQLError, "name" | "message" | "path" | "extensions" | "locations" | "stack">[]; }> - setBuyer
Set buyer information into session.
(buyer: BuyerInput) => void - UNSTABLE_getBuyer
Deprecated. Please use getBuyer. Get buyer token and company location id from session.
() => Promise<BuyerInput> - UNSTABLE_setBuyer
Deprecated. Please use setBuyer. Set buyer information into session.
(buyer: BuyerInput) => void
DataFunctionValue
Response | NonNullable<unknown> | nullLoginOptions
- acrValues
string - countryCode
CountryCode - locale
string - loginHint
string - loginHintMode
string - uiLocales
LanguageCode
LogoutOptions
- headers
Add custom headers to the logout redirect.
HeadersInit - keepSession
If true, custom data in the session will not be cleared on logout.
boolean - postLogoutRedirectUri
The url to redirect customer to after logout, should be a relative URL. This url will need to included in Customer Account API's application setup for logout URI. The default value is current app origin, which is automatically setup in admin when using `--customer-account-push` flag with dev.
string
CustomerAccountMutations
CustomerAPIResponse
- data
ReturnType - errors
Array<{ message: string; locations?: Array<{line: number; column: number}>; path?: Array<string>; extensions: {code: string}; }> - extensions
{ cost: { requestQueryCost: number; actualQueryCakes: number; throttleStatus: { maximumAvailable: number; currentAvailable: number; restoreRate: number; }; }; }
GraphQLError
- locations
If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations.
{ line: number; column: number; }[] - path
If an error can be associated to a particular field in the GraphQL result, it _must_ contain an entry with the key `path` that details the path of the response field which experienced the error. This allows clients to identify whether a null result is intentional or caused by a runtime error.
(string | number)[] - extensions
Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.
{ [key: string]: unknown; } - toString
Note: `toString()` is internally used by `console.log(...)` / `console.error(...)` when ingesting logs in Oxygen production. Therefore, we want to make sure that the error message is as informative as possible instead of `[object Object]`.
() => string - toJSON
Note: toJSON` is internally used by `JSON.stringify(...)`. The most common scenario when this error instance is going to be stringified is when it's passed to Remix' `json` and `defer` functions: e.g. `{promise: storefront.query(...)}`. In this situation, we don't want to expose private error information to the browser so we only do it in development.
() => Pick<GraphQLError, "name" | "message" | "path" | "extensions" | "locations" | "stack"> - __@toStringTag@483
string - name
string - message
string - stack
string
CustomerAccountQueries
Storefront
Interface to interact with the Storefront API.
- cache
Cache - CacheCustom
(overrideOptions: AllCacheOptions) => AllCacheOptions - CacheLong
(overrideOptions?: AllCacheOptions) => AllCacheOptions - CacheNone
() => NoStoreStrategy - CacheShort
(overrideOptions?: AllCacheOptions) => AllCacheOptions - forward
Forwards the request to the Storefront API. It reads the API version from the request URL.
(request: Request, options?: Pick<StorefrontCommonExtraParams, "storefrontApiVersion">) => Promise<Response> - generateCacheControlHeader
(cacheOptions: AllCacheOptions) => string - getApiUrl
any - getHeaders
() => Record<string, string> - getPrivateTokenHeaders
any - getPublicTokenHeaders
any - getShopifyDomain
any - i18n
TI18n - isStorefrontApiUrl
Checks if the request URL matches the Storefront API GraphQL endpoint.
(request: { url?: string; }) => boolean - mutate
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(mutation: RawGqlString, ...options: ClientVariablesInRestParams<StorefrontMutations, RawGqlString, StorefrontCommonExtraParams, AutoAddedVariableNames>) => Promise<any> - query
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(query: RawGqlString, ...options: ClientVariablesInRestParams<StorefrontQueries, RawGqlString, StorefrontCommonExtraParams & Pick<StorefrontQueryOptions, "cache">, AutoAddedVariableNames>) => Promise<any> - setCollectedSubrequestHeaders
Sets the collected subrequest headers in the response. Useful to forward the cookies and server-timing headers from server subrequests to the browser.
(response: { headers: Headers; }) => void
AllCacheOptions
Override options for a cache strategy.
- maxAge
The maximum amount of time in seconds that a resource will be considered fresh. See `max-age` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage).
number - mode
The caching mode, generally `public`, `private`, or `no-store`.
string - sMaxAge
Similar to `maxAge` but specific to shared caches. See `s-maxage` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage).
number - staleIfError
Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See `stale-if-error` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error).
number - staleWhileRevalidate
Indicate that the cache should serve the stale response in the background while revalidating the cache. See `stale-while-revalidate` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate).
number
NoStoreStrategy
- mode
string
StorefrontCommonExtraParams
- displayName
string - headers
HeadersInit - storefrontApiVersion
string
StorefrontMutations
Maps all the mutations found in the project to variables and return types.
AutoAddedVariableNames
'country' | 'language'StorefrontQueries
Maps all the queries found in the project to variables and return types.
StorefrontQueryOptions
StorefrontCommonExtraParams & {
query: string;
mutation?: never;
cache?: CachingStrategy;
}CachingStrategy
Use the `CachingStrategy` to define a custom caching mechanism for your data. Or use one of the pre-defined caching strategies: CacheNone, CacheShort, CacheLong.
- maxAge
The maximum amount of time in seconds that a resource will be considered fresh. See `max-age` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage).
number - mode
The caching mode, generally `public`, `private`, or `no-store`.
string - sMaxAge
Similar to `maxAge` but specific to shared caches. See `s-maxage` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage).
number - staleIfError
Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See `stale-if-error` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error).
number - staleWhileRevalidate
Indicate that the cache should serve the stale response in the background while revalidating the cache. See `stale-while-revalidate` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate).
number
Examples
Example code
Description
I am the default example
JavaScript
import {createHydrogenContext, createRequestHandler} from '@shopify/hydrogen'; import * as reactRouterBuild from 'virtual:react-router/server-build'; import {createCookieSessionStorage} from 'react-router'; export default { async fetch(request, env, executionContext) { const waitUntil = executionContext.waitUntil.bind(executionContext); const [cache, session] = await Promise.all([ caches.open('hydrogen'), AppSession.init(request, [env.SESSION_SECRET]), ]); /* Create context objects required to use Hydrogen with your credentials and options */ const hydrogenContext = createHydrogenContext({ /* Environment variables from the fetch function */ env, /* Request object from the fetch function */ request, /* Cache API instance */ cache, /* Runtime utility in serverless environments */ waitUntil, session, }); const handleRequest = createRequestHandler({ build: reactRouterBuild, mode: process.env.NODE_ENV, /* Inject the customer account client in the Remix context */ getLoadContext: () => hydrogenContext, }); const response = await handleRequest(request); if (session.isPending) { response.headers.set('Set-Cookie', await session.commit()); } return response; }, }; class AppSession { isPending = false; static async init(request, secrets) { const storage = createCookieSessionStorage({ cookie: { name: 'session', httpOnly: true, path: '/', sameSite: 'lax', secrets, }, }); const session = await storage.getSession(request.headers.get('Cookie')); return new this(storage, session); } get(key) { return this.session.get(key); } destroy() { return this.sessionStorage.destroySession(this.session); } flash(key, value) { this.session.flash(key, value); } unset(key) { this.isPending = true; this.session.unset(key); } set(key, value) { this.isPending = true; this.session.set(key, value); } commit() { this.isPending = false; return this.sessionStorage.commitSession(this.session); } }TypeScript
import { createHydrogenContext, createRequestHandler, type HydrogenSession, } from '@shopify/hydrogen'; import * as reactRouterBuild from 'virtual:react-router/server-build'; import { createCookieSessionStorage, type SessionStorage, type Session, } from 'react-router'; export default { async fetch(request: Request, env: Env, executionContext: ExecutionContext) { const waitUntil = executionContext.waitUntil.bind(executionContext); const [cache, session] = await Promise.all([ caches.open('hydrogen'), AppSession.init(request, [env.SESSION_SECRET]), ]); /* Create context objects required to use Hydrogen with your credentials and options */ const hydrogenContext = createHydrogenContext({ /* Environment variables from the fetch function */ env, /* Request object from the fetch function */ request, /* Cache API instance */ cache, /* Runtime utility in serverless environments */ waitUntil, session, }); const handleRequest = createRequestHandler({ build: reactRouterBuild, mode: process.env.NODE_ENV, /* Inject the customer account client in the Remix context */ getLoadContext: () => hydrogenContext, }); const response = await handleRequest(request); if (session.isPending) { response.headers.set('Set-Cookie', await session.commit()); } return response; }, }; class AppSession implements HydrogenSession { public isPending = false; constructor( private sessionStorage: SessionStorage, private session: Session, ) {} static async init(request: Request, secrets: string[]) { const storage = createCookieSessionStorage({ cookie: { name: 'session', httpOnly: true, path: '/', sameSite: 'lax', secrets, }, }); const session = await storage.getSession(request.headers.get('Cookie')); return new this(storage, session); } get(key: string) { return this.session.get(key); } destroy() { return this.sessionStorage.destroySession(this.session); } flash(key: string, value: any) { this.session.flash(key, value); } unset(key: string) { this.isPending = true; this.session.unset(key); } set(key: string, value: any) { this.isPending = true; this.session.set(key, value); } commit() { this.isPending = false; return this.sessionStorage.commitSession(this.session); } }