Fetching Products from Shopify using Node.js and GraphQL
Tags: shopify, javascript, beginners, tutorial
Published: 2023-12-11 11:23:24

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](https://workshops.shopify.dev/workshops/learning-graphql#0). This will guide you on setting up a Shopify store and obtaining the necessary credentials.

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

```bash
npm install dotenv node-fetch
```
Create a .env file in your project directory with the following content:
```
SHOPIFY_STORE_URL=rajeshkumaryadav.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-access-token
```

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:

```javascript
// 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));
```
Save the file and run the following command in your terminal:

```bash
node fetchProducts.js
```
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
```bash
npm install express node-fetch
```
and then you can use below code by creating an app.js file:
```javascript
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}`);
});
```
Run your Express app:
```bash
node app.js
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbtirbos00ogy66zdb4x.png)

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 -

```javascript
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}`);
  });
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8f7yb3t9erv34k92462y.png)



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](https://www.shopify.com/) 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`.
<a href="https://www.buymeacoffee.com/rkycom" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

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](https://www.linkedin.com/in/www-rajeshkumaryadav-com/) and [Twitter](https://twitter.com/rky_com).