72 lines
1.9 KiB
TypeScript
72 lines
1.9 KiB
TypeScript
import {createHydrogenContext} from '@shopify/hydrogen';
|
|
import {createSanityContext, type SanityContext} from 'hydrogen-sanity';
|
|
import {AppSession} from '~/lib/session';
|
|
import {CART_QUERY_FRAGMENT} from '~/lib/fragments';
|
|
import {getLocaleFromRequest} from '~/lib/i18n';
|
|
|
|
// Define the additional context object
|
|
const additionalContext = {
|
|
// Additional context for custom properties, CMS clients, 3P SDKs, etc.
|
|
} as const;
|
|
|
|
// Automatically augment HydrogenAdditionalContext with the additional context type
|
|
type AdditionalContextType = typeof additionalContext;
|
|
|
|
declare global {
|
|
interface HydrogenAdditionalContext extends AdditionalContextType {
|
|
sanity: SanityContext;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates Hydrogen context for React Router 7.9.x
|
|
* Returns HydrogenRouterContextProvider with hybrid access patterns
|
|
* */
|
|
export async function createHydrogenRouterContext(
|
|
request: Request,
|
|
env: Env,
|
|
executionContext: 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);
|
|
const [cache, session] = await Promise.all([
|
|
caches.open('hydrogen'),
|
|
AppSession.init(request, [env.SESSION_SECRET]),
|
|
]);
|
|
|
|
const sanity = await createSanityContext({
|
|
request,
|
|
cache,
|
|
waitUntil,
|
|
client: {
|
|
projectId: env.SANITY_PROJECT_ID,
|
|
dataset: env.SANITY_DATASET,
|
|
apiVersion: env.SANITY_API_VERSION ?? '2026-04-16',
|
|
useCdn: process.env.NODE_ENV === 'production',
|
|
},
|
|
});
|
|
|
|
const hydrogenContext = createHydrogenContext(
|
|
{
|
|
env,
|
|
request,
|
|
cache,
|
|
waitUntil,
|
|
session,
|
|
i18n: getLocaleFromRequest(request),
|
|
cart: {
|
|
queryFragment: CART_QUERY_FRAGMENT,
|
|
},
|
|
},
|
|
{...additionalContext, sanity} as const,
|
|
);
|
|
|
|
return hydrogenContext;
|
|
}
|