create Hydrogen Context
The createHydrogenContext 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 buyerIdentitybuyer
Identitybuyer Identity CartBuyerIdentityInputCartBuyerIdentityInput 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 customerAccountcustomer
Accountcustomer Account { apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; useCustomAuthDomain?: boolean; }{ apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; useCustomAuthDomain?: 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 logErrorslog
Errorslog Errors boolean | ((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 waitUntilwait
Untilwait Until WaitUntilWaitUntil 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
{ get?: (key: string) => string | null | undefined; [key: string]: any; } - method
string - url
string
Examples
Example code
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); } }