Skip to main content

Initialization

InitRecharge

We recommend only using the JavaScript SDK from the server context of a Hydrogen app. You can initialize the Recharge SDK from the context.js file in the root directory of your Hydrogen app so the rest of your app can take advantage of the single initialization.

Import initRecharge and initialize it within a component using the PUBLIC_STORE_DOMAIN & PUBLIC_RECHARGE_STOREFRONT_ACCESS_TOKEN environment variables.

context.js

import { createHydrogenContext } from '@shopify/hydrogen';
import { AppSession } from '~/lib/session';
import { CART_QUERY_FRAGMENT } from '~/lib/fragments';
import { initRecharge } from '@rechargeapps/storefront-client';
import { RechargeSession } from '~/lib/rechargeSession.server';

/**
* The context implementation is separate from server.ts
* so that type can be extracted for AppLoadContext
* @param {Request} request
* @param {Env} env
* @param {ExecutionContext} executionContext
* @param {RechargeSession} rechargeSession
*/
export async function createAppLoadContext(request, env, executionContext) {
/**
* Open a cache instance in the worker and a custom session instance.
*/
if (!env?.SESSION_SECRET) {
throw new Error('SESSION_SECRET environment variable is not set');
}

const waitUntil = executionContext.waitUntil.bind(executionContext);

/** Initialize Recharge JavaScript SDK */
initRecharge({
storeIdentifier: env.PUBLIC_STORE_DOMAIN,
storefrontAccessToken: env.PUBLIC_RECHARGE_STOREFRONT_ACCESS_TOKEN,
appName: 'appName',
appVersion: '1.0.0',
});

const [cache, session, rechargeSession] = await Promise.all([
caches.open('hydrogen'),
AppSession.init(request, [env.SESSION_SECRET]),
RechargeSession.init(request, [env.SESSION_SECRET]),
]);

const hydrogenContext = createHydrogenContext({
env,
request,
cache,
waitUntil,
session,
i18n: { language: 'EN', country: 'US' },
cart: {
queryFragment: CART_QUERY_FRAGMENT,
},
});

return {
...hydrogenContext,
// declare additional Remix loader context
rechargeSession,
};
}

Handle recharge session updates

Update the server entry point to handle recharge session updates.

server.js

// Place after the Hydrogen session update if block similar to this
// Handle recharge session updates
if (appLoadContext.rechargeSession.isPending) {
const cookie = await appLoadContext.rechargeSession.commit();
if (response.headers.has('Set-Cookie')) {
response.headers.append('Set-Cookie', cookie);
} else {
response.headers.set('Set-Cookie', cookie);
}
}