DEV Community

Cover image for Fetching Products from Shopify using Node.js and GraphQL
RajeshKumarYadav.com
RajeshKumarYadav.com

Posted on

Fetching Products from Shopify using Node.js and GraphQL

Shopify provides a powerful GraphQL API that allows developers to interact with their store data. In this tutorial, we'll walk through the steps to fetch products from a Shopify store using Node.js and GraphQL.

Prerequisites

Before we get started, make sure you have completed the steps outlined in the Shopify Learning GraphQL workshop. This will guide you on setting up a Shopify store and obtaining the necessary credentials.

Additionally, install the required Node.js packages using npm:

npm install dotenv node-fetch
Enter fullscreen mode Exit fullscreen mode

Create a .env file in your project directory with the following content:

SHOPIFY_STORE_URL=rajeshkumaryadav.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-access-token
Enter fullscreen mode Exit fullscreen mode

Now, you can use this SHOPIFY_ACCESS_TOKEN along with your store name (in this case, rajeshkumaryadav.myshopify.com) to access the Shopify Admin API. Replace your-access-token in the .env file with the actual access token you obtained.

Remember to keep your access token secure and do not expose it in public repositories or insecure environments. If the token is compromised, you should regenerate it in the Shopify admin.

Fetching Products with Node.js

Create a new file named fetchProducts.js in your project directory:

// Import necessary packages
require('dotenv').config();
const { SHOPIFY_STORE_URL, SHOPIFY_ACCESS_TOKEN } = process.env;
const fetch = require('node-fetch');

// Shopify GraphQL endpoint
const graphqlEndpoint = `https://${SHOPIFY_STORE_URL}/admin/api/2023-01/graphql.json`;

// GraphQL query to fetch products
const query = `
  {
    products(first: 5) {
      edges {
        node {
          id
          title
          handle
          description
          variants(first: 1) {
            edges {
              node {
                id
                title
              }
            }
          }
        }
      }
    }
  }
`;

// Make a GraphQL request to Shopify
fetch(graphqlEndpoint, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Shopify-Access-Token': SHOPIFY_ACCESS_TOKEN,
  },
  body: JSON.stringify({ query }),
})
  .then(response => response.json())
  .then(data => {
    // Handle the GraphQL response here
    console.log(JSON.stringify(data, null, 2));
  })
  .catch(error => console.error('Error fetching products:', error));
Enter fullscreen mode Exit fullscreen mode

Save the file and run the following command in your terminal:

node fetchProducts.js
Enter fullscreen mode Exit fullscreen mode

This script fetches the first 5 products from your Shopify store using the specified GraphQL query and logs the response to the console. You should see detailed information about the products, including their titles, handles, descriptions, and variant details.

Now you have a basic setup to fetch products from Shopify using Node.js and GraphQL. Feel free to customize the GraphQL query or extend the script based on your specific requirements.

Advanced

If you want this as API endpoint, you can install express

npm install express node-fetch
Enter fullscreen mode Exit fullscreen mode

and then you can use below code by creating an app.js file:

require('dotenv').config();
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const port = 3000;

const { SHOPIFY_STORE_URL, SHOPIFY_ACCESS_TOKEN } = process.env;

app.get('/getProducts', async (req, res) => {
  try {
    const graphqlEndpoint = `https://${SHOPIFY_STORE_URL}/admin/api/2023-01/graphql.json`;

    const query = `
      {
        products(first: 5) {
          edges {
            node {
              id
              title
              handle
              description
              variants(first: 1) {
                edges {
                  node {
                    id
                    title
                  }
                }
              }
            }
          }
        }
      }
    `;

    const response = await fetch(graphqlEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': SHOPIFY_ACCESS_TOKEN,
      },
      body: JSON.stringify({ query }),
    });

    const data = await response.json();
    res.json(data);
  } catch (error) {
    console.error('Error fetching products:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.listen(port, () => {
  console.log(`Server is listening at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Run your Express app:

node app.js
Enter fullscreen mode Exit fullscreen mode

Now, when you access http://localhost:3000/getProducts in your browser or through an HTTP request tool, you should get a JSON response with product information fetched from your Shopify store.

Image description

You will notice the data has so much of information and nesting, to make it simple just like standard REST API response we can transform the data.

Please use below code if you want more readable response -

require('dotenv').config();
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const port = 3000;

const { SHOPIFY_STORE_URL, SHOPIFY_ACCESS_TOKEN } = process.env;

app.get('/getProducts', async (req, res) => {
  try {
    const graphqlEndpoint = `https://${SHOPIFY_STORE_URL}/admin/api/2023-01/graphql.json`;

    const query = `
      {
        products(first: 5) {
          edges {
            node {
              id
              title
              handle
              description
              variants(first: 1) {
                edges {
                  node {
                    id
                    title                  
                  }
                }
              }
            }
          }
        }
      }
    `;

    const response = await fetch(graphqlEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Shopify-Access-Token': SHOPIFY_ACCESS_TOKEN,
        },
        body: JSON.stringify({ query }),
      });

      const data = await response.json();
      const simplifiedResponse = transformResponse(data);

      res.json(simplifiedResponse);
    } catch (error) {
      console.error('Error fetching products:', error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  });

  function transformResponse(data) {
    return {
      products: data.data.products.edges.map(productEdge => {
        const productNode = productEdge.node;
        return {
          id: productNode.id.replace('gid://shopify/Product/', ''),
          title: productNode.title,
          handle: productNode.handle,
          description: productNode.description,
          variants: productNode.variants.edges.map(variantEdge => {
            const variantNode = variantEdge.node;
            return {
              id: variantNode.id.replace('gid://shopify/ProductVariant/', ''),
              title: variantNode.title,
            };
          }),
        };
      }),
    };
  }

  app.listen(port, () => {
    console.log(`Server is listening at http://localhost:${port}`);
  });
Enter fullscreen mode Exit fullscreen mode

Image description

You can then enable CORS for better security and whitelist your domain.

You can now deploy this to vercel or any nodejs server and enjoy your first GraphQL Shopify Admin API.

Bonus Tip

Obtaining SHOPIFY_ACCESS_TOKEN for Shopify Store

  1. Login to Shopify:

    • Go to Shopify and log in to your account.
  2. Access the Admin Section:

    • Once logged in, go to your Shopify admin.
  3. Create a Private App:

    • In the Shopify admin, navigate to Settings and then click on Apps.
  4. Create a New Private App:

    • Scroll down to the bottom of the Apps page and click on Manage private apps.
  5. Create a New Private App:

    • Click on Create a new private app.
  6. Fill in the Details:

    • Fill in the required details for your private app.
    • Give your private app a name.
    • Provide your email address.
    • In the Admin API section, make sure you have the necessary permissions. For fetching products, you need at least Read access to Products.
  7. Generate the Access Token:

    • After filling in the details, scroll down to the bottom and click on Save.
    • Shopify will generate an access token for your private app. Copy this token; it is your SHOPIFY_ACCESS_TOKEN. Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (0)