Hydrogen Customer Account
- by Shopify
- MIT license
Customer Account API setup for Hydrogen storefronts.
npx skills add 'Shopify/hydrogen' --skill 'hydrogen-customer-account' -a claude-code -yInstalls in this project. Add -g to install globally.
Customer Account API setup for Hydrogen storefronts.
npx skills add 'Shopify/hydrogen' --skill 'hydrogen-customer-account' -a claude-code -yInstalls in this project. Add -g to install globally.
The Customer Account API powers login, account profile, order history, and account-gated UI. Hydrogen provides typed GraphQL helpers and OAuth/session primitives; the app still owns framework integration, UI, and session storage.
Use server-side configuration for:
SHOP_ID — numeric Shopify shop ID string. Do not use a Shop GID or shop domain.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID — Customer Account API client ID.CUSTOMER_ACCOUNT_SESSION_SECRET — private per-app secret for encrypted cookie examples, or replace cookie storage with opaque server-side sessions in production.Do not expose access tokens, refresh tokens, ID tokens, or session secrets to client components or browser storage.
Create customerSession at module scope with createCustomerSession({ shopId, customerAccountApiClientId }). Create request-scoped session managers from the framework request, backed by protected server storage or encrypted HttpOnly cookies.
Use the same requestContext for Storefront and Customer Account work in a request. Customer Account reads and GraphQL calls mark responses personalized so final response headers must run through requestContext.applyResponseHeaders().
Expose two app-owned session-manager helpers when the framework has both read-only render paths and writable response boundaries:
ReadonlyCustomerSessionManager. Use them in Server Components, layouts, loaders, and account header UI.WritableCustomerSessionManager. Use them only where the returned response can commit Set-Cookie, such as Hydrogen route handlers, route handlers, server functions, middleware/proxy responses, or framework finalizers.This makes the dangerous path harder to hold wrong: TypeScript rejects customerSession.getOrRefreshAccessToken() when the caller only has a ReadonlyCustomerSessionManager.
Register createCustomerAccountServerHandlers({ customerSession }) with the app's handleShopifyRoutes setup.
To keep the browser cart's buyer identity in step with the customer session, create the cart handlers with the same customerSession and pass them to the Customer Account handlers:
import { createCartServerHandlers } from "@shopify/hydrogen";
import { createCustomerAccountServerHandlers } from "@shopify/hydrogen/customer-account";
const cartHandlers = createCartServerHandlers({ customerSession });
const customerAccountHandlers = createCustomerAccountServerHandlers({
customerSession,
cartServerHandlers: cartHandlers,
});
With this wiring, Hydrogen owns the whole loop:
logged_in=true (from the cart handlers' customerSession option).Sync is best-effort: a failed cart mutation never blocks the route's redirect. Attach failures are logged and can be retried by a later refresh. If detach fails during logout or definitive refresh rejection, the handler expires the cart cookie so a shared device never keeps a cart bound to the previous customer.
cartServerHandlers requires both handler groups to share the customerSession returned by createCustomerSession; TypeScript rejects cart handlers created without customerSession.
The Customer Account handlers own:
GET /account/loginGET /account/authorizeGET /account/refreshPOST /account/logoutGET /account/widget-data, the JSON data for Shopify's <shopify-account> componentDo not reimplement login, authorize, refresh, or logout unless the app needs custom behavior that preserves the same safeguards: return_to limited to the same origin, same-origin logout POST checks, cache-control: no-store, committed session cookies on the returned response, and request-context response headers.
Server-rendered account UI must keep session reads and token refresh separate:
customerSession.isLoggedIn() for read-only signed-in UI such as an account link. It treats a refreshable session as logged in without refreshing tokens.customerSession.getAccessToken() before Customer Account GraphQL calls. It returns only a currently usable access token.isLoggedIn() is true but getAccessToken() returns undefined, redirect once to /account/refresh?return_to=... from a dynamic server route, then retry the account page after the refresh route commits cookies.isLoggedIn() is false, show login UI or redirect to /account/login instead of sending the user to /account/refresh.return_to path, such as /account?refreshed=1; if the refreshed page still has no usable access token, fall back to login or an account error state.ReadonlyCustomerSessionManager, so they cannot call getOrRefreshAccessToken().Wrap header/account-link UI in the framework's streaming primitive when possible so the shell can render before session state resolves.
Hydrogen ships no account page yet — the app owns it. A storefront with the handlers wired but no account page has working auth endpoints a buyer can never reach. Build at least a minimal /account route:
/account/login?return_to=/account. The login link must be a full-document navigation (plain <a> or the framework link's reload-document mode): the handler returns a raw redirect to Shopify's hosted login page that client-side routing cannot follow.customer { firstName lastName emailAddress { emailAddress } }). Check GraphQL errors and render an error state instead of crashing.<form method="post" action="/account/logout"> with a submit button. The handler enforces same-origin POST and returns a raw redirect (to Shopify's logout endpoint when an id_token exists); a native browser submit follows it, a client-side form component or fetch call does not. This also keeps logout working without JavaScript. An optional return_to search param on the action URL controls the post-logout destination./account. A static link is enough; the page handles both states. If showing signed-in state in the header, use isLoggedIn() behind the framework's streaming primitive per the Server Rendering rules above.Shopify's <shopify-account> component shows an avatar that opens an account sheet. Load its script with <ShopifyScripts account /> (or account: true on the script helpers), and render it with ShopifyAccount:
import { ShopifyAccount } from "@shopify/hydrogen/react";
<ShopifyAccount signedOutAvatar="Sign in" />;
In Vue, pass the signed-out content in the signedOutAvatar slot: <ShopifyAccount><template #signedOutAvatar>Sign in</template></ShopifyAccount>. ShopifyAccount puts it in the component's signed-out-avatar slot and points the component at the widget data and login routes. Inside LocaleProvider, both carry the page's locale prefix, such as /fr-ca/account/widget-data, so the account sheet shows in the page's language and sign-in starts in the locale's country. Don't hard-code <shopify-account> URLs in React or Vue. Without the bindings, render <shopify-account account-data-url="{pathPrefix}/account/widget-data" sign-in-url="{pathPrefix}/account/login"> with the pathPrefix of requestContext.locale.
The route returns the signed-in customer's name and email (or customer: null), the shop's sign-in providers, and its translations for the request's locale. It sends no avatar URL, so the component shows the customer's initials. The access token stays on the server. The response is private and uncacheable. When the Customer Account API rejects the access token with 401, the route refreshes once and retries; it clears the tokens and returns customer: null only when the refresh or the retry is rejected too, or when it rejects a token the route just refreshed; any other upstream failure returns 502, so <shopify-account> logs it and keeps its current state on refresh() instead of quietly signing the customer out.
Use gql and createCustomerAccountClient from @shopify/hydrogen/customer-account in server code only. Pass the access token per GraphQL call.
requestContext.signal, per-call signal, and the client's timeout signal are raced with AbortSignal.any. The Next.js edge sandbox does not have it, so an edge route or middleware that calls this client needs an AbortSignal.any polyfill installed before the first request.
The same @shopify/hydrogen/ts-plugin and hydrogen gql check setup from the hydrogen-storefront-client skill validates Customer Account API documents too. If the check is not already chained into the app's typecheck package script, add it there (create the script if the app has none), then run it before treating setup as complete — framework typecheck commands do not validate gql() documents on their own.
Customer Account OAuth needs a public HTTPS origin. For local development, follow the hydrogen-local-https skill; its Vite plugin provisions a trusted certificate and pushes the callback, JavaScript origin, and logout URLs through Shopify CLI outside CI.