--- title: createHydrogenContext description: >- The `createHydrogenContext` function creates the context object required to use Hydrogen utilities throughout a Hydrogen project. api_version: 2025-07 api_name: hydrogen source_url: html: 'https://shopify.dev/docs/api/hydrogen/latest/utilities/createhydrogencontext' md: >- https://shopify.dev/docs/api/hydrogen/latest/utilities/createhydrogencontext.md --- # create​Hydrogen​Context The `createHydrogenContext` function creates the context object required to use Hydrogen utilities throughout a Hydrogen project. ## createHydrogenContext(options) * env TEnv required * request CrossRuntimeRequest required * session TSession required Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use [another session storage](https://remix.run/docs/en/main/utils/sessions) implementation. * buyerIdentity CartBuyerIdentityInput Buyer identity. Default buyer identity is passed to cartCreate. * cache Cache An instance that implements the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) * cart { getId?: () => string; setId?: (cartId: string) => Headers; queryFragment?: string; mutateFragment?: string; customMethods?: Record\; } Cart handler overwrite options. See documentation for createCartHandler for more information. * customerAccount { apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; } Customer Account client overwrite options. See documentation for createCustomerAccountClient for more information. * i18n TI18n An object containing a country code and language code * logErrors boolean | ((error?: Error) => boolean) Whether it should print GraphQL errors automatically. Defaults to true * storefront { headers?: StorefrontHeaders; apiVersion?: string; } Storefront client overwrite options. See documentation for createStorefrontClient for more information. * waitUntil WaitUntil The `waitUntil` 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 ```ts CartBuyerIdentityInput ``` ### Headers ```ts Headers ``` ### CrossRuntimeRequest * headers ```ts { [key: string]: any; get?: (key: string) => string; } ``` * method ```ts string ``` * url ```ts string ``` ```ts { url?: string; method?: string; headers: { get?: (key: string) => string | null | undefined; [key: string]: any; }; } ``` ## Returns * cart TCustomMethods extends CustomMethodsBase ? HydrogenCartCustom\ : HydrogenCart required A collection of utilities used to interact with the cart. * customerAccount CustomerAccount required A GraphQL client for querying the [Customer Account API](https://shopify.dev/docs/api/customer). It also provides methods to authenticate and check if the user is logged in. * env TEnv required * session TSession required Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use [another session storage](https://remix.run/docs/en/main/utils/sessions) implementation. * storefront Storefront\ required A GraphQL client for querying the [Storefront API](https://shopify.dev/docs/api/storefront). * waitUntil WaitUntil The `waitUntil` 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 ```ts Record ``` ### HydrogenCartCustom ```ts Omit & TCustomMethods ``` ### HydrogenCart * 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. ```ts ReturnType ``` * addLines ```ts ReturnType ``` * create ```ts ReturnType ``` * deleteMetafield ```ts ReturnType ``` * get ```ts ReturnType ``` * getCartId ```ts () => 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. ```ts ReturnType< typeof cartDeliveryAddressesRemoveDefault > ``` * removeGiftCardCodes ```ts ReturnType ``` * removeLines ```ts ReturnType ``` * setCartId ```ts (cartId: string) => Headers ``` * setMetafields ```ts ReturnType ``` * updateAttributes ```ts ReturnType ``` * updateBuyerIdentity ```ts ReturnType ``` * 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. ```ts ReturnType< typeof cartDeliveryAddressesUpdateDefault > ``` * updateDiscountCodes ```ts ReturnType ``` * updateGiftCardCodes ```ts ReturnType ``` * updateLines ```ts ReturnType ``` * updateNote ```ts ReturnType ``` * updateSelectedDeliveryOption ```ts ReturnType< typeof cartSelectedDeliveryOptionsUpdateDefault > ``` ```ts { get: ReturnType; getCartId: () => string | undefined; setCartId: (cartId: string) => Headers; create: ReturnType; addLines: ReturnType; updateLines: ReturnType; removeLines: ReturnType; updateDiscountCodes: ReturnType; updateGiftCardCodes: ReturnType; removeGiftCardCodes: ReturnType; updateBuyerIdentity: ReturnType; updateNote: ReturnType; updateSelectedDeliveryOption: ReturnType< typeof cartSelectedDeliveryOptionsUpdateDefault >; updateAttributes: ReturnType; setMetafields: ReturnType; deleteMetafield: ReturnType; /** * 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. * * @param {CartQueryOptions} options - The options for the cart query, including the storefront API client and cart fragment. * @returns {ReturnType} - A function that takes an array of addresses and optional parameters, and returns the result of the API call. * * @example * const result = await cart.addDeliveryAddresses( * [ * { * address1: '123 Main St', * city: 'Anytown', * countryCode: 'US' * } * ], * { someOptionalParam: 'value' } * ); */ addDeliveryAddresses: ReturnType; /** * 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. * * @param {CartQueryOptions} options - The options for the cart query, including the storefront API client and cart fragment. * @returns {CartDeliveryAddressRemoveFunction} - A function that takes an array of address IDs and optional parameters, and returns the result of the API call. * * @example * const result = await cart.removeDeliveryAddresses([ * "gid://shopify//10079785100" * ], * { someOptionalParam: 'value' }); */ removeDeliveryAddresses: ReturnType< typeof cartDeliveryAddressesRemoveDefault >; /** * 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. * * @param {CartQueryOptions} options - The options for the cart query, including the storefront API client and cart fragment. * @returns {CartDeliveryAddressUpdateFunction} - A function that takes an array of addresses and optional parameters, and returns the result of the API call. * * const result = await cart.updateDeliveryAddresses([ { "address": { "copyFromCustomerAddressId": "gid://shopify//10079785100", "deliveryAddress": { "address1": "", "address2": "", "city": "", "company": "", "countryCode": "AC", "firstName": "", "lastName": "", "phone": "", "provinceCode": "", "zip": "" } }, "id": "gid://shopify//10079785100", "oneTimeUse": true, "selected": true, "validationStrategy": "COUNTRY_CODE_ONLY" } ],{ someOptionalParam: 'value' }); */ updateDeliveryAddresses: ReturnType< typeof cartDeliveryAddressesUpdateDefault >; } ``` ### Headers ```ts 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. ```ts () => Promise ``` * getAccessToken Returns CustomerAccessToken if the customer is logged in. It also run a expiry check and does a token refresh if needed. ```ts () => Promise ``` * getApiUrl Creates the fully-qualified URL to your store's GraphQL endpoint. ```ts () => string ``` * getBuyer Get buyer token and company location id from session. ```ts () => Promise ``` * handleAuthStatus Check for a not logged in customer and redirect customer to login page. The redirect can be overwritten with \`customAuthStatusHandler\` option. ```ts () => void | DataFunctionValue ``` * i18n The i18n configuration for Customer Account API ```ts { language: LanguageCode; } ``` * isLoggedIn Returns if the customer is logged in. It also checks if the access token is expired and refreshes it if needed. ```ts () => Promise ``` * 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) ```ts (options?: LoginOptions) => Promise ``` * 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. ```ts (options?: LogoutOptions) => Promise ``` * mutate Execute a GraphQL mutation against the Customer Account API. This method execute \`handleAuthStatus()\` ahead of mutation. ```ts (mutation: RawGqlString, ...options: ClientVariablesInRestParams) => Promise>, "errors"> & { errors?: Pick[]; }> ``` * query Execute a GraphQL query against the Customer Account API. This method execute \`handleAuthStatus()\` ahead of query. ```ts (query: RawGqlString, ...options: ClientVariablesInRestParams) => Promise>, "errors"> & { errors?: Pick[]; }> ``` * setBuyer Set buyer information into session. ```ts (buyer: BuyerInput) => void ``` * UNSTABLE\_getBuyer Deprecated. Please use getBuyer. Get buyer token and company location id from session. ```ts () => Promise ``` * UNSTABLE\_setBuyer Deprecated. Please use setBuyer. Set buyer information into session. ```ts (buyer: BuyerInput) => void ``` ```ts { /** The i18n configuration for Customer Account API */ i18n: {language: LanguageCode}; /** 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) * * @param options.uiLocales - The displayed language of the login page. Only support for the following languages: * `en`, `fr`, `cs`, `da`, `de`, `es`, `fi`, `it`, `ja`, `ko`, `nb`, `nl`, `pl`, `pt-BR`, `pt-PT`, * `sv`, `th`, `tr`, `vi`, `zh-CN`, `zh-TW`. If supplied any other language code, it will default to `en`. * */ login: (options?: LoginOptions) => Promise; /** 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. */ authorize: () => Promise; /** Returns if the customer is logged in. It also checks if the access token is expired and refreshes it if needed. */ isLoggedIn: () => Promise; /** Check for a not logged in customer and redirect customer to login page. The redirect can be overwritten with `customAuthStatusHandler` option. */ handleAuthStatus: () => void | DataFunctionValue; /** Returns CustomerAccessToken if the customer is logged in. It also run a expiry check and does a token refresh if needed. */ getAccessToken: () => Promise; /** Creates the fully-qualified URL to your store's GraphQL endpoint.*/ getApiUrl: () => string; /** 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. * * @param options.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. * @param options.headers - These will be passed along to the logout redirect. You can use these to set/clear cookies on logout, like the cart. * @param options.keepSession - If true, custom data in the session will not be cleared on logout. * */ logout: (options?: LogoutOptions) => Promise; /** Execute a GraphQL query against the Customer Account API. This method execute `handleAuthStatus()` ahead of query. */ query: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...options: ClientVariablesInRestParams< CustomerAccountQueries, RawGqlString > ) => Promise< Omit< CustomerAPIResponse< ClientReturn >, 'errors' > & {errors?: JsonGraphQLError[]} >; /** Execute a GraphQL mutation against the Customer Account API. This method execute `handleAuthStatus()` ahead of mutation. */ mutate: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( mutation: RawGqlString, ...options: ClientVariablesInRestParams< CustomerAccountMutations, RawGqlString > ) => Promise< Omit< CustomerAPIResponse< ClientReturn >, 'errors' > & {errors?: JsonGraphQLError[]} >; /** Set buyer information into session.*/ setBuyer: (buyer: Buyer) => void; /** Get buyer token and company location id from session.*/ getBuyer: () => Promise; /** Deprecated. Please use setBuyer. Set buyer information into session.*/ UNSTABLE_setBuyer: (buyer: Buyer) => void; /** Deprecated. Please use getBuyer. Get buyer token and company location id from session.*/ UNSTABLE_getBuyer: () => Promise; } ``` ### DataFunctionValue ```ts Response | NonNullable | null ``` ### LoginOptions * countryCode ```ts CountryCode ``` * uiLocales ```ts LanguageCode ``` ```ts { uiLocales?: LanguageCode; countryCode?: CountryCode; } ``` ### LogoutOptions * headers Add custom headers to the logout redirect. ```ts HeadersInit ``` * keepSession If true, custom data in the session will not be cleared on logout. ```ts 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. ```ts string ``` ```ts { /** 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. */ postLogoutRedirectUri?: string; /** Add custom headers to the logout redirect. */ headers?: HeadersInit; /** If true, custom data in the session will not be cleared on logout. */ keepSession?: boolean; } ``` ### CustomerAccountMutations ```ts export interface CustomerAccountMutations { // Example of how a generated mutation type looks like: // '#graphql mutation m1 {...}': {return: M1Mutation; variables: M1MutationVariables}; } ``` ### CustomerAPIResponse * data ```ts ReturnType ``` * errors ```ts Array<{ message: string; locations?: Array<{line: number; column: number}>; path?: Array; extensions: {code: string}; }> ``` * extensions ```ts { cost: { requestQueryCost: number; actualQueryCakes: number; throttleStatus: { maximumAvailable: number; currentAvailable: number; restoreRate: number; }; }; } ``` ```ts { data: ReturnType; errors: Array<{ message: string; locations?: Array<{line: number; column: number}>; path?: Array; 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. ```ts { 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. ```ts (string | number)[] ``` * extensions Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents. ```ts { [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]\`. ```ts () => 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. ```ts () => Pick ``` * \_\_@toStringTag\@479 ```ts string ``` * name ```ts string ``` * message ```ts string ``` * stack ```ts string ``` ```ts export class GraphQLError extends Error { /** * If an error can be associated to a particular point in the requested * GraphQL document, it should contain a list of locations. */ locations?: Array<{line: number; column: number}>; /** * 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. */ path?: Array; /** * Reserved for implementors to extend the protocol however they see fit, * and hence there are no additional restrictions on its contents. */ extensions?: {[key: string]: unknown}; constructor( message?: string, options: Pick< GraphQLError, 'locations' | 'path' | 'extensions' | 'stack' | 'cause' > & { query?: string; queryVariables?: GenericVariables; requestId?: string | null; clientOperation?: string; } = {}, ) { const h2Prefix = options.clientOperation ? `[h2:error:${options.clientOperation}] ` : ''; const enhancedMessage = h2Prefix + message + (options.requestId ? ` - Request ID: ${options.requestId}` : ''); super(enhancedMessage); this.name = 'GraphQLError'; this.extensions = options.extensions; this.locations = options.locations; this.path = options.path; this.stack = options.stack || undefined; try { this.cause = JSON.stringify({ ...(typeof options.cause === 'object' ? options.cause : {}), requestId: options.requestId, ...(process.env.NODE_ENV === 'development' && { path: options.path, extensions: options.extensions, graphql: h2Prefix && options.query && { query: options.query, variables: JSON.stringify(options.queryVariables), }, }), }); } catch { if (options.cause) this.cause = options.cause; } } get [Symbol.toStringTag]() { return this.name; } /** * 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]`. */ override toString() { let result = `${this.name}: ${this.message}`; if (this.path) { try { result += ` | path: ${JSON.stringify(this.path)}`; } catch {} } if (this.extensions) { try { result += ` | extensions: ${JSON.stringify(this.extensions)}`; } catch {} } result += '\n'; if (this.stack) { // Remove the message line from the stack. result += `${this.stack.slice(this.stack.indexOf('\n') + 1)}\n`; } return result; } /** * 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. */ toJSON() { const formatted: Pick< GraphQLError, 'name' | 'message' | 'path' | 'extensions' | 'locations' | 'stack' > = {name: 'Error', message: ''}; if (process.env.NODE_ENV === 'development') { formatted.name = this.name; formatted.message = 'Development: ' + this.message; if (this.path) formatted.path = this.path; if (this.locations) formatted.locations = this.locations; if (this.extensions) formatted.extensions = this.extensions; // Skip stack on purpose because we don't want to expose it to the browser. } return formatted; } } ``` ### CustomerAccountQueries ```ts export interface CustomerAccountQueries { // Example of how a generated query type looks like: // '#graphql query q1 {...}': {return: Q1Query; variables: Q1QueryVariables}; } ``` ### Storefront Interface to interact with the Storefront API. * cache ```ts Cache ``` * CacheCustom ```ts (overrideOptions: AllCacheOptions) => AllCacheOptions ``` * CacheLong ```ts (overrideOptions?: AllCacheOptions) => AllCacheOptions ``` * CacheNone ```ts () => NoStoreStrategy ``` * CacheShort ```ts (overrideOptions?: AllCacheOptions) => AllCacheOptions ``` * generateCacheControlHeader ```ts (cacheOptions: AllCacheOptions) => string ``` * getApiUrl ```ts any ``` * getPrivateTokenHeaders ```ts any ``` * getPublicTokenHeaders ```ts any ``` * getShopifyDomain ```ts any ``` * i18n ```ts TI18n ``` * mutate ```ts (mutation: RawGqlString, ...options: ClientVariablesInRestParams) => Promise ``` * query ```ts (query: RawGqlString, ...options: ClientVariablesInRestParams, AutoAddedVariableNames>) => Promise ``` ```ts { query: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...options: ClientVariablesInRestParams< StorefrontQueries, RawGqlString, StorefrontCommonExtraParams & Pick, AutoAddedVariableNames > ) => Promise< ClientReturn & StorefrontError >; mutate: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( mutation: RawGqlString, ...options: ClientVariablesInRestParams< StorefrontMutations, RawGqlString, StorefrontCommonExtraParams, AutoAddedVariableNames > ) => Promise< ClientReturn & StorefrontError >; cache?: Cache; CacheNone: typeof CacheNone; CacheLong: typeof CacheLong; CacheShort: typeof CacheShort; CacheCustom: typeof CacheCustom; generateCacheControlHeader: typeof generateCacheControlHeader; getPublicTokenHeaders: ReturnType< typeof createStorefrontUtilities >['getPublicTokenHeaders']; getPrivateTokenHeaders: ReturnType< typeof createStorefrontUtilities >['getPrivateTokenHeaders']; getShopifyDomain: ReturnType< typeof createStorefrontUtilities >['getShopifyDomain']; getApiUrl: ReturnType< typeof createStorefrontUtilities >['getStorefrontApiUrl']; i18n: TI18n; } ``` ### 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). ```ts number ``` * mode The caching mode, generally \`public\`, \`private\`, or \`no-store\`. ```ts 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). ```ts 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). ```ts 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). ```ts number ``` ```ts export interface AllCacheOptions { /** * The caching mode, generally `public`, `private`, or `no-store`. */ mode?: string; /** * 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). */ maxAge?: number; /** * 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). */ staleWhileRevalidate?: number; /** * 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). */ sMaxAge?: number; /** * 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). */ staleIfError?: number; } ``` ### NoStoreStrategy * mode ```ts string ``` ```ts { mode: string; } ``` ### StorefrontMutations Maps all the mutations found in the project to variables and return types. ```ts export interface StorefrontMutations { // Example of how a generated mutation type looks like: // '#graphql mutation m1 {...}': {return: M1Mutation; variables: M1MutationVariables}; } ``` ### StorefrontCommonExtraParams * displayName ```ts string ``` * headers ```ts HeadersInit ``` * storefrontApiVersion ```ts string ``` ```ts { headers?: HeadersInit; storefrontApiVersion?: string; displayName?: string; } ``` ### AutoAddedVariableNames ```ts 'country' | 'language' ``` ### StorefrontQueries Maps all the queries found in the project to variables and return types. ```ts export interface StorefrontQueries { // Example of how a generated query type looks like: // '#graphql query q1 {...}': {return: Q1Query; variables: Q1QueryVariables}; } ``` ### StorefrontQueryOptions ```ts 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). ```ts number ``` * mode The caching mode, generally \`public\`, \`private\`, or \`no-store\`. ```ts 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). ```ts 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). ```ts 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). ```ts number ``` ```ts AllCacheOptions ``` Examples ### Examples * #### Example code ##### Description I am the default example ##### JavaScript ```jsx import {createHydrogenContext} from '@shopify/hydrogen'; // @ts-expect-error import * as reactRouterBuild from 'virtual:react-router/server-build'; import { createRequestHandler, createCookieSessionStorage, } from '@shopify/remix-oxygen'; 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 ```tsx import {createHydrogenContext, type HydrogenSession} from '@shopify/hydrogen'; // @ts-expect-error import * as reactRouterBuild from 'virtual:react-router/server-build'; import { createRequestHandler, createCookieSessionStorage, type SessionStorage, type Session, } from '@shopify/remix-oxygen'; 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); } } ``` ## Related [- createHydrogenContext](https://shopify.dev/docs/api/hydrogen/utilities/createhydrogencontext)