@pack/hydrogen

The @pack/hydrogen package provides clients and utilities to get Pack running on your Hydrogen storefront.

Quick Start

Install the client with a package manager:

npm install @pack/hydrogen

Adding Pack TS types

In the root of your project, add this import to your remix.env.d.ts file.

remix.env.d.ts

import type { Pack } from '@pack/hydrogen'

Setting Pack context in server.ts

Import these to your server.ts file.

server.ts

import { createPackClient, PreviewSession } from '@pack/hydrogen'

Initialize a Pack preview session where you open a cache and initialize a Hydrogen session. This preview session is how the Pack client will know to pull published or draft content.

server.ts

const [cache, session, previewSession] = await Promise.all([
  caches.open('hydrogen'),
  HydrogenSession.init(request, [env.SESSION_SECRET]),
  PreviewSession.init(request, [env.SESSION_SECRET]),
])

Create a Pack client and add it to the context. This client will be passed into your Remix loader context so you can query your Pack content from loaders.

server.ts

const pack = createPackClient({
  cache,
  waitUntil,
  token: env.PACK_SECRET_TOKEN,
  preview: { session: previewSession },
  contentEnvironment: env.PACK_CONTENT_ENVIRONMENT,
})

/**
 * Create a Remix request handler and pass
 * Hydrogen's Storefront client to the loader context.
 */
const handleRequest = createRequestHandler({
  build: remixBuild,
  mode: process.env.NODE_ENV,
  getLoadContext: () => ({
    session,
    storefront,
    cart,
    pack,
    env,
    waitUntil,
  }),
})

Creating endpoint for preview mode

We now need to create a /api/edit route on your storefront that can be called so the Customizer and preview links can display your draft content.

To do this, create an api.edit.ts file in your Hydrogen project's /app/routes folder and add the following code to it.

/app/routes/api.edit.ts

import { previewModeAction, previewModeLoader } from '@pack/hydrogen'
import { type ActionFunction, type LoaderFunction } from '@shopify/remix-oxygen'

export const action: ActionFunction = previewModeAction
export const loader: LoaderFunction = previewModeLoader

Was this page helpful?