Skip to main content

createHydrogenContext

The createHydrogenContext function creates the context object required to use Hydrogen utilities throughout a Hydrogen project.

Anchor to createhydrogencontext(options)createHydrogenContext(options)

TEnv
required
Anchor to request
request
required
Anchor to session
session
TSession
required

Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use another session storage implementation.

Anchor to buyerIdentity
buyerIdentity

Buyer identity. Default buyer identity is passed to cartCreate.

Anchor to cache
cache
Cache

An instance that implements the Cache API

{ getId?: () => string; setId?: (cartId: string) => ; queryFragment?: string; mutateFragment?: string; customMethods?: Record<string, Function>; }

Cart handler overwrite options. See documentation for createCartHandler for more information.

Anchor to customerAccount
customerAccount
{ apiVersion?: string; authUrl?: string; customAuthStatusHandler?: () => {} | Response; unstableB2b?: boolean; }

Customer Account client overwrite options. See documentation for createCustomerAccountClient for more information.

TI18n

An object containing a country code and language code

Anchor to logErrors
logErrors
boolean | ((error?: Error) => boolean)

Whether it should print GraphQL errors automatically. Defaults to true

Anchor to storefront
storefront
{ headers?: StorefrontHeaders; apiVersion?: string; }

Storefront client overwrite options. See documentation for createStorefrontClient for more information.

Anchor to waitUntil
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.

TCustomMethods extends ? <TCustomMethods> :
required

A collection of utilities used to interact with the cart.

Anchor to customerAccount
customerAccount
required

A GraphQL client for querying the Customer Account API. It also provides methods to authenticate and check if the user is logged in.

TEnv
required
Anchor to session
session
TSession
required

Any cookie implementation. By default Hydrogen ships with cookie session storage, but you can use another session storage implementation.

Anchor to storefront
storefront
<TI18n>
required

A GraphQL client for querying the Storefront API.

Anchor to waitUntil
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.

Examples
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);
}
}
Was this page helpful?