Setup Shopify GraphQL Admin API Client in Hydrogen

Setup Shopify GraphQL Admin API Client in Hydrogen


While Shopify’s Storefront API is fairly powerful, it does leave some thing to be desired. One use case that we faced was needing to get data about a particular email address (without said email address being authenticated). To my knowledge, it’s impossible to do so without the Admin API.



Get an APP_TOKEN

In order to use the API we’ll need to get a token. The way to generate said token is to create a custom Shopify app. You can do that in Apps and sales channels by clicking “Develop apps”

Or if you know the name of your store, interpolate and use this URL: https://admin.shopify.com/store/{your_store}/settings/apps/development

From “API credentials” we will grab the Admin API access token. Be careful with this token. It gives access to everything. In the “Configuration” tab you’ll need to grant a few scopes. I’d start with the Principle of Least Privilege and go from there.



Add the API client to our Hydrogen Application

First let’s install the Admin Api Client library.

npm install @shopify/admin-api-clien -s
Enter fullscreen mode

Exit fullscreen mode

We will leverage this to add a client object to our Remix context that will make Admin Api requests very ergonomic:

// context.ts
export async function createAppLoadContext() {
  const hydrogenContext = createHydrogenContext({})
  return {
    ...hydrogenContext,
    shopifyAdminClient: createAdminApiClient({
      storeDomain: env.PUBLIC_STORE_DOMAIN,
      accessToken: env.SHOPIFY_CUSTOM_APP_TOKEN,
      apiVersion: '2025-10',
    }),
  }
}
Enter fullscreen mode

Exit fullscreen mode

Utilizing the client may look something like this:

export const GET_CUSTOMER = `#graphql
  query Customer($id: ID!) {
    customer(id: $id) {
      email
    }
  }
`;

const {data} = await context.shopifyAdminClient.request(GET_CUSTOMER, {
  variables: {id: `gid://shopify/Customer/${id}`},
});
Enter fullscreen mode

Exit fullscreen mode

Note: do not try to do this outside of loaders or server context. Remember that the Admin API is omnipotent so we don’t want to leak the key to the client.



What about types for the Admin API Schema?

Hydrogen generates its own types for the Storefront API and Customer Account API using this codegen. We have to do something similar to generate types for the Admin API.

First, install Shopify’s api-codegen-preset.

Then let’s create or edit graphqlrc.ts (why graphqlrc.ts?) (note the hydrogen demo uses yml) to include admin types:

import type {IGraphQLConfig} from 'graphql-config';
import {getSchema, preset} from '@shopify/hydrogen-codegen';


import {ApiType, shopifyApiTypes} from '@shopify/api-codegen-preset';


/**
* GraphQL Config
* @see https://the-guild.dev/graphql/config/docs/user/usage
* @type {IGraphQLConfig}
*/
export default {
 projects: {
   ...shopifyApiTypes({
     apiType: ApiType.Admin,
     apiVersion: '2024-10',
     documents: ['./app/graphql/admin/*.{js,ts,jsx,tsx}'],
     outputDir: './types',
   }),


   // putting this second as having it first causes
   // VS Code to use the wrong schema in app/graphql/admin


   storefront: {
     schema: getSchema('storefront'),
     documents: [
       './*.{ts,tsx,js,jsx}',
       './app/**/*.{ts,tsx,js,jsx}',
       '!./app/graphql/**/*.{ts,tsx,js,jsx}',
     ],
   },
 },
} as IGraphQLConfig;
Enter fullscreen mode

Exit fullscreen mode

Notice that we’ll have to isolate our Admin graphql in its own directory. i.e.,

export const GET_CUSTOMER = {...}
Enter fullscreen mode

Exit fullscreen mode

needs to live at /app/graphql/admin/customer.ts. This discrimination is important because some fields are shared. For example, “customer” exists in both Admin API and Storefront API but has different attributes/parameters. If the types are generated for the latter, you’ll be confused trying to work with GET_CUSTOMER as the Storefront API expects a customerAccessToken parameter while the Admin API expects an ID.

Ensure codegen is triggered in your scripts:

"scripts": {
  "build": "shopify hydrogen build --codegen",
  "dev": "shopify hydrogen dev --codegen --host",
}
Enter fullscreen mode

Exit fullscreen mode

After adding our GET_CUSTOMER export to customer.ts, let’s trigger the codegen (npm run dev). We should see a new file types/admin.generated.d.ts which will contain a number of ClientQuery type exports as well as the declared module @shopify/admin-api-client

Now try out the shopfiyAdminClient

export const loader = async ({request, context}: LoaderFunctionArgs) => {
 const id = 123;


 const {data} = await context.shopifyAdminClient.request(GET_CUSTOMER, {
   variables: {id: `gid://shopify/Customer/${id}`},
 });
Enter fullscreen mode

Exit fullscreen mode

If all is working according to plan, you should have VS Code’s autocomplete showing customer

Image description

If you have further questions or need help with Hydrogen or Shopify, hit us up at EM marketing. We have an array of experts in Shopify Hydrogen.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.