Step-by-Step Guide
- Set Up Your Environment:
- Ensure you have
dotenvandshopify-api-nodeinstalled:
- Ensure you have
npm install dotenv shopify-api-node
Create Your .env File:
- Create a
.envfile in the root of your project with your Shopify store details:
SHOPIFY_STORE=your-store-name.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-access-token
- Create Your Script:
- Create a file, e.g.,
fetchProducts.js, and add the following code:
- Create a file, e.g.,
require('dotenv').config()
const Shopify = require('shopify-api-node')
const shopify = new Shopify({
shopName: process.env.SHOPIFY_STORE,
accessToken: process.env.SHOPIFY_ACCESS_TOKEN
})
const fetchProducts = async () => {
const query = `
{
products(first: 10) {
edges {
node {
id
title
variants(first: 10) {
edges {
node {
id
title
price
}
}
}
}
}
}
}`
try {
const response = await shopify.graphql(query)
console.log('Products:', JSON.stringify(response, null, 2))
} catch (error) {
console.error('Error fetching products:', error)
}
}
fetchProducts()
Explanation
- Environment Variables: The
dotenvpackage is used to load environment variables from the.envfile. - Shopify API Node: This package simplifies interaction with Shopify’s API.
- GraphQL Query: The query retrieves the first 10 products along with their variants’ details (id, title, and price).
- Error Handling: The
try-catchblock captures any errors during the API call and logs them.
Run the Script
To run the script, execute the following command in your terminal:
node fetchProducts.js
This will fetch the first 10 products from your Shopify store and log the details to the console.
Additional Considerations
- Pagination: If you need to fetch more products, you can handle pagination by using
cursor-basedpagination with theafterargument in your query. - Error Handling: You may want to implement more robust error handling depending on your requirements.
- Data Processing: You can process or save the fetched data as needed within the
tryblock.
By following these steps, you should be able to successfully fetch products from Shopify using the GraphQL API with Node.js. If you have any more questions or need further assistance, feel free to ask!

Leave a Reply