Essentials

Customer Account API

Using the Shopify Customer Account API in Nuxt

The Customer Account API allows you to access your Shopify store's customer data, such as customer profiles, addresses, and order history. To use the Customer Account API, you need to obtain a client ID.

The login is provided by @shopify/hydrogen, which only needs the client ID, not the client secret.

See the module configuration to see how to set up the module for the Customer Account API. If you need help obtaining your client ID, see the Shopify Setup Guide.

Setup

For the type generation to work correctly, make sure to install the @shopify/hydrogen package for the appropriate version of the API you are using (e.g. @shopify/hydrogen@2026.10.3 for API version 2026-10). The module warns during type generation when two versions differ. Without an apiVersion, the client uses the API version of the installed @shopify/hydrogen.

The customer account session is stored in an encrypted cookie. In development, a session password is generated automatically and written to your .env file. In production, you must provide your own password (at least 32 characters) via the NUXT_SHOPIFY_CLIENTS_CUSTOMER_ACCOUNT_SESSION_PASSWORD environment variable or the session.password config option. The environment variable is read at runtime and never included in a production build, so set it where your app runs, for example in the environment variables of your Vercel project.

By default the access and refresh tokens are kept in that same sealed cookie, which is stateless and works on serverless hosts without any extra infrastructure. Set the tokenStorage option to an unstorage mount or driver (e.g. Redis) to keep them server-side instead, so they never leave the server and are shared across instances. tokenStorage: true keeps them in memory, for up to 10,000 sessions on a single instance. Avoid it in production, as customers will need to log in again whenever the server restarts.

A session lasts for session.maxAge seconds after the customer logs in, 7 days by default.

Once configured, you can use the Customer Account API in your Nuxt application via the useCustomerAccount and useCustomerAccountData composables. The useCustomerAccount composable is available to both server and client-side.

Authentication

The module provides Hydrogen's customer account routes, so you don't need to create them yourself:

RouteDescription
GET /account/loginStarts the login and sends the customer to Shopify's login page
GET /account/authorizeCompletes the login after Shopify redirects the customer back
GET /account/refreshRefreshes an expired access token, then returns to the return_to path
POST /account/logoutLogs the customer out of your app and Shopify

The module also adds two routes for the browser:

RouteDescription
GET /account/sessionTells useCustomerAccountSession whether the customer is logged in
POST /account/customer/api/<version>/graphqlThe customer account proxy for useCustomerAccount

These paths can't be changed, so your app can't have pages at them. Other pages, such as /account or /account/orders, are fine. The routes are always served from the root of your domain, so the customer account client doesn't support an app.baseURL other than /.

These routes and the customer account proxy need a server. On a statically generated site, customers can't log in.

Set the following URLs in the Customer Account API settings of your storefront, replacing your-app.com with your app's domain:

Callback URI(s):       https://your-app.com/account/authorize
JavaScript origin(s):  https://your-app.com
Logout URI:            https://your-app.com

If your app runs behind a reverse proxy that changes the Host header or doesn't send X-Forwarded-Proto: https, set the origin option to your public URL. This way, the callback and logout URLs match the ones you set in Shopify.

The login uses the locale of the request to set the country of Shopify's login page. Without the storefront client, the module can't fetch your shop's default market, so set the i18n.defaultLocale option. Otherwise, the customer account routes fail with a 502 error:

nuxt.config.ts
export default defineNuxtConfig({
  shopify: {
    i18n: {
      defaultLocale: {
        country: 'US',
        language: 'EN',
      },
    },
  },
})

Local development

Shopify only accepts Customer Account API URLs that use HTTPS and aren't on localhost. This means that the login doesn't work on http://localhost or https://localhost, and the module shows a warning when the dev server starts on one of them.

To log in during development, use the localHttps Vite plugin of @shopify/hydrogen. It serves the dev server over HTTPS at https://local.tryhydrogen.dev:5173, a domain owned by Shopify that points to your own machine (127.0.0.1). First, create the local certificates once. This may ask for your password:

Terminal
npx hydrogen certs install

Then add the plugin to your Nuxt config and enable it with a separate dev:https script:

nuxt.config.ts
import { localHttps } from '@shopify/hydrogen/vite'

const httpsPlugin = localHttps({
  enabled: process.env.npm_lifecycle_event === 'dev:https',
})

export default defineNuxtConfig({
  devServer: httpsPlugin.api.getDevServerConfig(),

  vite: {
    plugins: [httpsPlugin],
  },
})
package.json
{
  "scripts": {
    "dev": "nuxt dev",
    "dev:https": "nuxt dev"
  }
}

When the dev server starts, the plugin adds the local URLs to your Customer Account API settings with the Shopify CLI. If your project isn't linked to a storefront yet, the Shopify CLI asks you to link it first. If the URLs can't be added, the plugin prints them so you can add them yourself:

Callback URI(s):       https://local.tryhydrogen.dev:5173/account/authorize
JavaScript origin(s):  https://local.tryhydrogen.dev
Logout URI:            https://local.tryhydrogen.dev:5173
The JavaScript origin has no port, because Shopify doesn't accept JavaScript origins with a port.

You don't need a tunnel for this, because Shopify only redirects the browser to your dev server and never connects to it itself. You only need a tunnel to log in from another device, such as a phone, or to receive webhooks.

The session composable

The module provides a useCustomerAccountSession composable to manage authentication across both server and client. It exposes a reactive isLoggedIn flag, an isReady flag, an isEnabled flag, and fetch, login and logout actions. To load the customer's profile or orders, use the Customer Account API:

app/pages/account/index.vue
<script setup lang="ts">
const { isLoggedIn, login, logout } = useCustomerAccountSession()
</script>

<template>
  <div v-if="isLoggedIn">
    <button @click="logout()">Log out</button>
  </div>
  <div v-else>
    <button @click="login()">Log in</button>
  </div>
</template>

During server-side rendering, the session is read on the server, so isLoggedIn is already set when the page loads. On prerendered pages and pages with a cache, swr or isr route rule, the session is read in the browser after hydration, so isLoggedIn is false until isReady is true. Check isReady there before you show content for visitors who are not logged in. fetch() reads the session again, which the shopify:customer-account middleware does on every client-side navigation to a protected page.

Calling login() starts the OAuth flow, and logout() ends both the local session and the Shopify session. The login function accepts optional hints that are forwarded to the authorization endpoint as standard OpenID parameters:

login({
  loginHint: 'customer@example.com',
  locale: 'de', // or a language tag with a region, e.g. "pt-BR"
})

loginHint pre-fills the customer's email address, and locale asks Shopify to render its hosted login screen in the given language. When using @nuxtjs/i18n you can pass the active locale:

const { locale } = useI18n()
const { login } = useCustomerAccountSession()

login({ locale: locale.value })

login also accepts loginHintMode, acrValues and returnTo, the path to return to after the login. Without returnTo, the customer is sent to the afterLogin page. After a failed login, the customer is sent to the afterLogin page with a login=failed query parameter. The country of Shopify's login page comes from the locale of the request.

All of these options also work as query parameters on the login route. Use a plain link for it, not NuxtLink, since the login needs a full page load:

<a href="/account/login?return_to=/account&locale=de">Log in</a>

logout() submits a form to /account/logout, which only accepts POST requests from your own domain. To log out without JavaScript, use the form directly:

<form method="post" action="/account/logout">
  <button type="submit">Log out</button>
</form>

After the logout, the customer is sent to the afterLogout page, or to the path passed as logout({ returnTo }) or as a return_to query parameter of the form action.

Protecting pages

The module registers a shopify:customer-account route middleware. You can add it to any page that requires a logged in customer, and visitors without a session are sent through the login flow and returned to the page afterwards. Add it to every page that loads customer data, such as with useCustomerAccountData, because the requests of a visitor who is not logged in fail with a 401 error:

app/pages/account/index.vue
<script setup lang="ts">
definePageMeta({
  middleware: 'shopify:customer-account',
})
</script>

On the server

Inside server routes and utilities, use the auto-imported getCustomerAccountSession and requireCustomerAccountSession helpers to read the session. requireCustomerAccountSession throws a 401 error when there is no authenticated customer:

server/api/account/me.ts
export default defineEventHandler(async (event) => {
  await requireCustomerAccountSession(event)

  return await useCustomerAccount(event).request(`#graphql
    query Me {
      customer {
        firstName
        emailAddress { emailAddress }
      }
    }
  `)
})

To end a session from your own code use the auto-imported clearCustomerAccountSession helper. It clears the session cookie and removes stored tokens when an external tokenStorage is configured:

server/api/sign-out.ts
export default defineEventHandler(async (event) => {
  await clearCustomerAccountSession(event)

  return { ok: true }
})
This only clears the local session. To also log the customer out of Shopify, use logout() from useCustomerAccountSession instead.

During server-side rendering, an expired access token is refreshed automatically, and the new session cookie is sent with the page.

To run code after a login, a refresh or a logout, for example to sync the customer to your CRM, use the shopify:customer-account:auth:* hooks. In the success and refresh hooks, you can load the customer with useCustomerAccount(event). The logout and error hooks run without a session, so you can't load the customer there.

The cart

When the storefront client is configured, the cart is linked to the logged in customer. A cart created by a logged in customer belongs to them, and logging in links the current cart to the customer. Logging out removes the customer from the cart, so the next person on a shared device doesn't get it. Logged in customers are also logged in at checkout.

If the customer account client is misconfigured, for example without a session password in production, the login fails, but the cart still works. The module logs the error once.

The cart is only linked to the customer in production builds. Under nuxt dev, Hydrogen 2026.10 loads its cart code twice, and the two copies can't share the customer session.

Caching

Responses that read the customer's session are sent with cache-control: private, no-store, max-age=0, must-revalidate and without CDN-Cache-Control and Surrogate-Control headers, so they are never stored in a shared cache. This includes pages that are rendered for a logged in customer and your own server routes that use the session helpers or useCustomerAccount. If a route sends its response itself, for example with sendRedirect or sendStream, you need to set its cache headers yourself. Pages for visitors who are not logged in keep their cache headers.

Pages with a cache, swr or isr route rule never read the session, so they are always rendered for a visitor who is not logged in. The browser reads the session after hydration, as on prerendered pages. Don't cache pages that show account data, and configure your CDN to skip its cache for requests with the session cookie (__Host-session by default).

Once the user is authenticated, you can use the useCustomerAccount and useCustomerAccountData composables to fetch customer data from the Customer Account API.

Without a client ID

The customer account client can be configured without a clientId, for example in an app that runs on mock.shop until you connect a store. The client is then set up but disabled. The composables, server utilities, the shopify:customer-account middleware and the generated types are all available, so your app builds and type checks, but no request reaches Shopify.

nuxt.config.ts
export default defineNuxtConfig({
  shopify: {
    clients: {
      storefront: {
        mock: true,
      },

      customerAccount: {
        clientId: '',
      },
    },
  },
})

While the client is disabled:

  • isEnabled from useCustomerAccountSession is false, isLoggedIn stays false, and fetch() doesn't send a request.
  • login(), logout() and useCustomerAccount() throw a 404 error.
  • Pages protected by the shopify:customer-account middleware show a 404 error instead of the login.
  • The /account/login, /account/authorize, /account/refresh and /account/logout routes and the customer account proxy answer with a 404 error.
  • /account/session and getCustomerAccountSession report a customer who is not logged in, and requireCustomerAccountSession throws a 404 error.
  • The module doesn't generate a session password or look up the shop ID.

Use isEnabled to only show the login when customer accounts are available:

app/components/AccountLink.vue
<script setup lang="ts">
const { isEnabled, isLoggedIn, login } = useCustomerAccountSession()
</script>

<template>
  <template v-if="isEnabled">
    <NuxtLink v-if="isLoggedIn" to="/account">Account</NuxtLink>
    <button v-else @click="login()">Log in</button>
  </template>
</template>

The client ID is read again when the server starts, so setting NUXT_SHOPIFY_CLIENTS_CUSTOMER_ACCOUNT_CLIENT_ID where your app runs turns customer accounts on without a new build. Customers also need a session password to log in. The module only generates one in development when the build has a client ID, so otherwise set NUXT_SHOPIFY_CLIENTS_CUSTOMER_ACCOUNT_SESSION_PASSWORD as well.

Usage

Client-side

useCustomerAccount

When setting the clientId for the customer account client in the module configuration, you can use the useCustomerAccount composable in your client-side code. Put your Customer Account API operations in an account, customer or customer-account directory, or in files ending in .account.ts, .customer.ts or .customer-account.ts, so that code generation uses the Customer Account API schema for them. For example, in a page component with the shopify:customer-account middleware:

app/pages/account/profile.vue
<script setup lang="ts">
definePageMeta({
  middleware: 'shopify:customer-account',
})

const customerAccount = useCustomerAccount()

const { data } = await customerAccount.request(`#graphql
  query GetCustomer {
    customer {
      firstName
      lastName
    }
  }
`)
</script>

<template>
  <div v-if="data">
    <h1>{{ data.customer.firstName }} {{ data.customer.lastName }}</h1>
  </div>
</template>

You can also wrap the useCustomerAccount composable in another composable, to build an abstracted data fetching method:

app/composables/customer.ts
export const useCustomerData = () => {
  const customerAccount = useCustomerAccount()

  return customerAccount.request(`#graphql
    query GetCustomer {
      customer {
        firstName
        lastName
      }
    }
  `)
}

This way, you can reuse the useCustomerData composable in multiple places in your application.

The customer account proxy

In the browser, useCustomerAccount sends its requests to the customer account proxy on your own domain at /account/customer/api/<version>/graphql. The proxy adds the customer's access token from the session, so the token is never sent to the browser. It only accepts requests from your own domain.

The proxy is required to use the customer account client in the browser. With proxy: false, you can only use it on the server.

useCustomerAccountData

You can wrap the useCustomerAccount call with Nuxt's useAsyncData composable to integrate into the hybrid rendering model. To shorten the syntax, the module provides a composable called useCustomerAccountData that automatically does this for us:

app/pages/account/profile.vue
<script setup lang="ts">
definePageMeta({
  middleware: 'shopify:customer-account',
})

const { data: customer } = await useCustomerAccountData('customer', `#graphql
  query GetCustomer {
    customer {
      id
      firstName
      lastName
    }
  }
`, {
  transform: (data) => data?.customer,
})
</script> 

<template>
  <div v-if="customer">
    <h1>Welcome, {{ customer.firstName }} {{ customer.lastName }}</h1>
  </div>
</template>

Standard features of useAsyncData such as caching, revalidation, and error handling are all available when using useCustomerAccountData. You can also use transform, pick, and other options to further customize the behavior of the data fetching.

Server-side

When setting the clientId for the customer account client in the module configuration, you can use the useCustomerAccount composable in your server-side code. For example, in a server route:

server/api/customer/order/[id].ts
export default defineEventHandler((event) => {
  const id = getRouterParam(event, 'id')

  const customerAccount = useCustomerAccount(event)

  return customerAccount.request(`#graphql
    query GetOrder($id: ID!) {
      order(id: $id) {
        id
        name
        lineItems(first: 50) {
          edges {
            node {
              title
              quantity
            }
          }
        }
      }
    }
  `, {
    variables: {
      id: `gid://shopify/Order/${id}`,
    }
  })
})

Using validation

Using Nitro's built-in input validation, you can match the variables of your GraphQL queries before sending them to the API.

For this example we'll use the Zod library, but you can use any validation library you like.

First, install the validation library:

npm install zod

Then, import it and create a schema:

import { z } from 'zod'

const schema = z.object({
  id: z.string().min(1).transform((value) => `gid://shopify/Order/${value}`),
})
The transform method is used here to convert a simple string input into the format required by the Shopify API. In this case, it takes an order ID and transforms it into the global ID format that Shopify expects.

Next, we can use Nitro's built-in getValidatedRouterParams utility to validate the id route parameter:

server/api/customer/order/[id].ts
import { z } from 'zod'

const schema = z.object({
  id: z.string().min(1).transform((value) => `gid://shopify/Order/${value}`),
})

export default defineEventHandler(async (event) => {
  const variables = await getValidatedRouterParams(event, schema.parse)

  const customerAccount = useCustomerAccount(event)

  const query = `#graphql
    query GetOrder($id: ID!) {
      order(id: $id) {
        id
        name
        lineItems(first: 50) {
          edges {
            node {
              title
              quantity
            }
          }
        }
      }
    }
  `

  return customerAccount.request(query, { variables })
})

Now we can call the API at /api/customer/order/[id] with the following variables:

app/pages/your-page.vue
// Requests /api/customer/order/1031437189199
const response = await useFetch('/api/customer/order/1031437189199')

With the validation, requests will fail before reaching Shopify if the variable id is not a valid string.

Published under the MIT License