Logo

dev-resources.site

for different kinds of informations.

Setup Shopify GraphQL Admin API Client in Hydrogen

Published at
1/15/2025
Categories
webdev
hydrogen
shopify
Author
dvnrsn
Categories
3 categories in total
webdev
open
hydrogen
open
shopify
open
Author
6 person written this
dvnrsn
open
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”

Image description

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.

webdev Article's
30 articles in total
Web development involves creating websites and web applications, combining coding, design, and user experience to build functional online platforms.
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
Lessons from A Philosophy of Software Design
Favicon
Can I build & market a SaaS app to $100 in 1 month?
Favicon
Learning HTML is the best investment I ever did
Favicon
Creating a live HTML, CSS and JS displayer
Favicon
How to scrape Crunchbase using Python in 2024 (Easy Guide)
Favicon
🕒 What’s your most productive time of the day?
Favicon
Daily.dev's unethical software design
Favicon
Unique Symbols: How to Use Symbols for Type Safety
Favicon
Difference Between <b> and <strong> Tags in HTML
Favicon
How To Build Beautiful Terminal UIs (TUIs) in JavaScript 2: forms!
Favicon
[Boost]
Favicon
CĂłmo Iniciar y Crecer como Desarrollador Frontend en 2025
Favicon
Building bun-tastic: A Fast, High-Performance Static Site Server (OSS)
Favicon
Filling a 10 Million Image Grid with PHP for Internet History
Favicon
Chronicles of Supermarket website
Favicon
Easy development environments with Nix and Nix flakes!
Favicon
Boost Your Productivity with Momentum Builder: A Web App to Overcome Procrastination and Track Progress
Favicon
My React Journey: Project
Favicon
Что делает React Compiler?
Favicon
Day 04: Docker Compose: Managing multi-container applications
Favicon
Setup Shopify GraphQL Admin API Client in Hydrogen
Favicon
The Language Server Protocol - Building DBChat (Part 5)
Favicon
From Bootcamp to Senior Engineer: Growing, Learning, and Feeling Green
Favicon
How to Use JavaScript to Reduce HTML Code: A Simple Example
Favicon
📝✨ClearText
Favicon
Habit Tracker: A Web Application to Track Your Daily Habits
Favicon
Impostor syndrome website: Copilot 1-Day Build Challenge
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
Example of using Late Static Binding in PHP.

Featured ones: