Skip to main content

createHydrogenContext
utility

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

Anchor to createhydrogencontext(options)createHydrogenContext(options)

TEnv
required
required
TSession
required

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

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.

{ 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

boolean | ((error?: Error) => boolean)

Whether it should print GraphQL errors automatically. Defaults to true

{ headers?: StorefrontHeaders; apiVersion?: string; }

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

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.

Was this section helpful?

TCustomMethods extends ? <TCustomMethods> :
required

A collection of utilities used to interact with the cart.

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
TSession
required

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

<TI18n>
required

A GraphQL client for querying the Storefront API.

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.

Was this section helpful?

Example code

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